C# Reference ยท Operators and Expressions
Operator overloading
Reference for C# operator overloading: which operators you can define, the pairing rules, static abstract interfaces, checked operators and compound assignment.
A type can give its own meaning to operators such as +, == and < by declaring a public static method named operator followed by the symbol. The compiler then lets you write a + b for your own types. Used with care it makes math-like types (vectors, money, fractions, durations) read naturally.
Operator overloading never changes the language's rules: precedence and associativity stay the same, and you cannot invent new operators.
public static Vec operator +(Vec a, Vec b) => new(a.X + b.X, a.Y + b.Y);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public static ResultType operator +(Left a, Right b) { ... } // binary public static ResultType operator -(Operand a) { ... } // unary public static bool operator ==(T a, T b) { ... } // must pair with != public static ResultType operator checked +(Left a, Right b) { ... } // C# 11
| Category | Operators you can overload |
|---|---|
| Unary | +, -, !, ~, ++, --, true, false |
| Binary | +, -, *, /, %, &, |, ^, <<, >>, >>> |
| Comparison | == and !=, < and >, <= and >= (each must be defined in pairs) |
| Conversions | implicit and explicit (see user-defined conversions) |
You cannot overload =, &&, \|\|, ??, ?:, ., new, is, as, typeof, sizeof or =>.
Usage notes
- At least one parameter of the operator (or its result for
++/--) must be the containing type. Operators are alwayspublic static. - Compound assignment
+=is not overloaded separately in a normal class or struct:a += bisa = a + b. C# 14 adds user-defined compound assignment operators (public void operator +=(int n)) that modify the instance in place, mainly for large mutable types. - Define
==and!=together, and also overrideEqualsandGetHashCodeso that all agree. Records and record structs do this for you. &&and||use your&and|together withtrueandfalse. Rarely needed.<and>must be defined in pairs, as must<=and>=.- A
checkedvariant is used inside acheckedcontext. If you omit it, the plain operator is used everywhere. - Operators defined on an interface as
static abstractmembers make generic math possible:T Add<T>(T a, T b) where T : IAdditionOperators<T,T,T>. - Keep operations intuitive. Adding two
Moneyvalues is fine; making+send an email is not. - Extension blocks in C# 14 can add operators to types you do not own.