New in .NET 10.0 [4]: New operator overloads in C# 14.0

C# 14.0 also offers operator overloads for compound assignment operators.

listen Print view

(Image: Pincasso/Shutterstock)

1 min. read
By
  • Dr. Holger Schwichtenberg

The programming language C# has supported operator overloads since its first version in 2002 with the keyword operator.

The Dotnet Doctor – Holger Schwichtenberg
Der Dotnet-Doktor – Holger Schwichtenberg

Dr. Holger Schwichtenberg is the technical director of the expert network www.IT-Visions.de, which supports numerous medium-sized and large companies with consulting and training services as well as software development, drawing on the expertise of 53 renowned experts. Thanks to his appearances at numerous national and international conferences, as well as more than 90 specialist books and over 1,500 specialist articles, Holger Schwichtenberg is one of the best-known experts for .NET and web technologies in Germany.

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)

Don't miss any news – follow us on Facebook, LinkedIn or Mastodon.

This article was originally published in German. It was translated with technical assistance and editorially reviewed before publication.