skip to content

In C# 14, what changes when a class declares `public void operator +=(double reading)` instead of relying on its static `operator +` for `stats += reading`?

level: seniorimportance: nice to knowfreq 15%

answer

  1. new object versus same object
  2. instance, void, one parameter
  3. only when the target is a variable
  4. aliases see the mutation

basics

~20 s

Without it, stats += reading compiles to stats = stats + reading, creating a new object. A C# 14 instance operator += mutates the object in place, so every alias sees the change; property targets still use the static operator.

solid answer

~50 s

Before C# 14 compound assignments could not be overloaded: `x += y` called the binary `operator +` and assigned its result back, which for a class means allocating a new object. C# 14 lets a type declare `public void operator +=(double reading)`: an instance method with no `static` (CS0106 if present), a `void` return (CS9310 otherwise) and one parameter. When the target is a **variable**, such as a local, a field or an array element, the compiler prefers the instance operator and the object is mutated in place, so `alias` and `stats` both see the update. When the target is a property or indexer, it is not a variable, so the compiler falls back to the static `+` plus the setter, and with no static `+` it reports CS0019. Nothing checks that `+=` and `+` agree, and instance `++` follows the same rules, except that `x++` uses it only when its result is unused.

code

csharp · 30 lines
csharp
var hourly = new Stats();
var alias = hourly;
hourly += 21.0;                       // instance operator +=, mutates in place
Console.WriteLine($"{ReferenceEquals(hourly, alias)} {alias.Count}");

var daily = new ImmutableStats(0, 0);
var before = daily;
daily += 21.0;                        // falls back to daily = daily + 21.0
Console.WriteLine($"{ReferenceEquals(daily, before)} {before.Count}");

var station = new Station();
station.Today += 18.5;                // a property is not a variable: static operator +
Console.WriteLine(station.Today.Count);

sealed class Stats
{
    public int Count { get; private set; }
    public double Sum { get; private set; }
    public void operator +=(double reading) { Count++; Sum += reading; }
    public static Stats operator +(Stats s, double reading)
    {
        Console.WriteLine("  static + called");
        return new Stats { Count = s.Count + 1, Sum = s.Sum + reading };
    }
}
sealed record ImmutableStats(int Count, double Sum)
{
    public static ImmutableStats operator +(ImmutableStats s, double reading) => new(s.Count + 1, s.Sum + reading);
}
sealed class Station { public Stats Today { get; set; } = new(); }

go deeper

for a junior

Recall that x += y on a user-defined type has always meant x = x + y, and that C# 14 added a way for a type to change that.

for a middle

Explain the declaration rules for the new operator, instance, void and one parameter, and the CS0106 and CS9310 errors that enforce them.

for a senior

Predict which operator runs for locals, properties and postfix increments, and spot the aliasing change when a class gains an instance +=.

for a principal

Decide whether a shared library's mutable types should adopt C# 14 compound operators, weighing fewer allocations against callers that relied on += producing a new object.

## Compound assignment before C# 14 A **compound assignment** such as `stats += reading` is shorthand that the compiler expands. Before C# 14, a type could not overload `+=` at all. For a user-defined type the compiler used the binary operator and assigned the result back: ```csharp stats += reading; // compiled as: stats = Stats.op_Addition(stats, reading); ``` For an immutable value such as a `Celsius` struct that is exactly right. For a large mutable aggregate, such as a dashboard's running statistics or a numeric buffer, it means the `+` operator must build and return a **new object** every time, copying its state, even though the caller is about to discard the old one. The csharplang proposal for the feature names that allocation and copy as its motivation. ## The C# 14 instance operator C# 14 adds **user-defined compound assignment operators** for `+=`, `-=`, `*=`, `/=`, `%=`, `&=`, `|=`, `^=`, `<<=`, `>>=` and `>>>=`. Their declaration rules differ from every other operator: - It is an **instance** member: adding `static` is error CS0106, "The modifier 'static' is not valid for this item". - It returns **`void`**: any other return type is CS9310, "The return type for this operator must be void". - It takes **one parameter**, the right-hand side. - It must be `public`, and it may be `virtual`, `override` or `abstract` like a method. - `+=`, `-=`, `*=` and `/=` may also have a `checked` form, paired with the regular one. Compiling the declaration with `LangVersion` 13 reports CS9260, "Feature 'user-defined compound assignment operators' is not available in C# 13.0". ## How the compiler chooses For `x += y`, the compiler follows a fixed order: 1. If `x` is classified as a **variable** (a local, a parameter, a field or an array element), it looks for an applicable instance `operator +=` on the type of `x` and calls it on `x`. 2. If there is none, or `x` is not a variable, it falls back to the binary `operator +` and assigns the result to `x`, through the setter for a property. 3. If neither exists, the statement is error CS0019, "Operator '+=' cannot be applied to operands of type...". So `station.Today += 18.5`, where `Today` is a property, calls the static `+` and then the setter, even when the class also declares an instance `+=`. ## The aliasing consequence The two paths give different results whenever two variables refer to the same object: | Code | Static `operator +` only | Instance `operator +=` | |---|---|---| | `var alias = stats; stats += 21.0;` | `stats` points to a new object; `alias` keeps the old values | `stats` and `alias` are the same object, and both show the update | | `ReferenceEquals(stats, alias)` afterwards | `false` | `true` | Adding an instance `+=` to an existing class is therefore a **behaviour change** for callers, not only a performance tweak: code that kept a reference to a previous snapshot will now see it change. For a struct the alias is a separate copy either way, so the difference is about copying, not about sharing. ## Increment and decrement C# 14 also allows instance `void operator ++()` and `void operator --()`. When `x` is a variable, the compiler prefers them for `++x`, and for `x++` only when the result is not used. In `var old = counter++;` the old value must survive the increment, so the static `operator ++` runs instead. ## When to declare one - **Do** declare it on large mutable types, such as accumulators, buffers and tensors, where avoiding a copy matters and callers expect mutation. - **Keep** the static binary operator alongside it, so properties, indexers and expressions such as `a + b` keep working; the compiler does not check that the two agree. - **Do not** add it to immutable value-like types such as `Celsius`: the static operator already gives the right semantics. - **Document** the mutation, because code written before C# 14 compiled `+=` as a fresh assignment. The interview point is that `x += y` is no longer guaranteed to mean `x = x + y` for user-defined types. A candidate who can say when each form is chosen, a variable target versus a property, a used versus an unused postfix result, and what that does to aliases, understands the feature rather than its syntax.

  • Why does `var old = counter++;` ignore a C# 14 instance `operator ++` on a class?
    The expression must produce the value before the increment. An instance operator mutates the object in place, so for a class there would be no earlier value left to return. When the result of a postfix increment is used, the compiler therefore uses the static `operator ++`; a bare `counter++;` statement prefers the instance one.
  • What happens to `station.Today += 1.0` if the class has an instance `operator +=` but no static `operator +`?
    A property is not a variable, so the instance operator is not a candidate and the compiler looks for a binary `+` to combine with the setter. With none declared it reports CS0019. Declaring the static operator, or assigning the property to a local first, makes the statement compile.

A static operator + is like saving an edited report under a new file name and repointing your own bookmark: colleagues who bookmarked the old file still see the old figures. An instance operator += edits the shared file in place, so everyone holding the link sees the new figures at once.

  • Believing += could always be overloaded separately from + in C#.
  • Assuming an instance += is a pure optimisation with no visible behaviour change.
  • Declaring the compound operator static and returning the new instance.
  • Expecting a property target to use the instance += operator.
  • Claiming the compiler forces += and + to agree.

Assumes C# 14 on .NET 10; before C# 14 compound assignment always used the binary operator, and the instance form is error CS9260 under LangVersion 13.