Skip to content

User-defined compound assignment C# 14.0performancenew scenarios

Define custom behavior for compound assignment operators like += and -=.

Previously, compound assignment operators like += and -= were always desugared by the compiler into the corresponding binary operator and assignment. For example, x += y became x = x + y. This meant the type had no control over the compound assignment and could not optimize it.

C# 14 allows types to define compound assignment operators directly, enabling in-place mutation that avoids allocating a new instance.

Code

C#
var buffer = new TextBuffer("Hello");
buffer += " World"; // Calls the custom += operator, mutates in place

public class TextBuffer
{
    private StringBuilder sb;

    public TextBuffer(string text) => sb = new StringBuilder(text);

    // Custom compound assignment — appends in place
    public static void operator +=(ref TextBuffer left, string right)
        => left.sb.Append(right);

    // Binary operator still needed for x = a + b
    public static TextBuffer operator +(TextBuffer left, string right)
        => new TextBuffer(left.sb.ToString() + right);
}
C#
var buffer = new TextBuffer("Hello");
buffer = buffer + " World"; // Always creates a new instance

public class TextBuffer
{
    private StringBuilder sb;

    public TextBuffer(string text) => sb = new StringBuilder(text);

    // += always desugared to: buffer = buffer + " World"
    public static TextBuffer operator +(TextBuffer left, string right)
        => new TextBuffer(left.sb.ToString() + right);
}

Notes

  • The compound assignment operator takes its first parameter by ref to allow in-place mutation
  • Defining += does not automatically define + or vice versa — both must be declared if needed
  • Particularly useful for collection-like types or builders where creating a new instance per operation is wasteful

More information