Summary#
Compound assignment updates a variable or property in place: x op= y is exactly x = x op y. The
arithmetic forms (+= -= *= /= %=) require a numeric lvalue; ??= (null-coalescing assignment) assigns
the right side only when the left is null.
Signature#
x += y // x = x + y (also string concatenation when x is a string)
x -= y // x = x - y
x *= y // x = x * y
x /= y // x = x / y (int/int truncates, like SQL)
x %= y // x = x % y (remainder)
x ??= y // x = x ?? y — assign y only when x is nullDescription#
- The left side must be an assignable lvalue — a variable or a property.
+= -= *= /= %=follow the arithmetic rules of their operator: numeric operands, numeric widening (long/decimal/double), and int÷int truncation for/=(SQL parity).+=on a string is concatenation.??=assigns only when the left side is null — a non-null left keeps its value; the right side is evaluated only when needed (short-circuit). Value-equivalent tox = x ?? yfor variable/property targets.- Decompile normalizes to the expanded
x = x op yform.
Examples#
int Mod() { int x = 17; x %= 5; return x; } // 2
string Keep() { string? s = "have"; s ??= "fallback"; return s; } // "have" (non-null kept)
string Fill(string? s) { s ??= "fallback"; return s; } // "fallback" when s is null
decimal RunningTotal(decimal[] amounts) {
decimal total = 0;
foreach (var a in amounts) { total += a; }
return total;
}See also#
- ++ / -- (increment / decrement) —
++/--, the± 1special case - Numeric types & literal suffixes — the numeric types the arithmetic forms operate on