New in .NET 10.0 [4]: New operator overloads in C# 14.0
C# 14.0 also offers operator overloads for compound assignment operators.
(Image: Pincasso/Shutterstock)
- Dr. Holger Schwichtenberg
The programming language C# has supported operator overloads since its first version in 2002 with the keyword operator.
In C# 14.0, Microsoft has now discovered an opportunity for improvement: Developers can now define their own operator implementations for the compound assignment operators +=, -=, *=, /=, %=, &=, |=, ^=, <<=,>>=, and >>>=.=,>
Previously, the operator implementations of the base operator (i.e., + for +=, - for -=, & for &=, etc.) were always called. This will continue to happen, but only if there is no custom operator implementation for the compound assignment operator.
Videos by heise
This allows for more control over memory usage: With compound assignment operators, the operation between two objects can be implemented in such a way that no new object is created, but an existing object is reused.
The compound assignment operators are (unlike other operators) not static and return void because they manipulate the object itself.
The following code snippet uses the User Defined Compound Assignment Operators:
namespace NET10_Console;
/// <summary>
/// Klasse mit OperatorĂĽberladung fĂĽr +, ++ und +=
/// </summary>
public class Kontostand
{
public string IBAN { get; set; }
public decimal Betrag { get; set; }
public Kontostand(string iBAN, decimal betrag)
{
Betrag = betrag;
IBAN = iBAN;
}
// ALT: OperatorĂĽberladung fĂĽr +
public static Kontostand operator +(Kontostand a, Kontostand b)
{
if (a == null || b == null)
throw new ArgumentNullException();
return new Kontostand(a.IBAN, a.Betrag + b.Betrag);
}
// NEU: OperatorĂĽberladung fĂĽr ++
public void operator ++()
{
this.Betrag += 1;
}
// NEU: OperatorĂĽberladung fĂĽr +=
public void operator +=(decimal b)
{
this.Betrag += b;
}
public override string ToString()
{
return $"Konto {IBAN}: {Betrag:c}"; // formatiert als Währung
(mki)