When overloading operators on a C# struct such as Celsius, which operators must come in pairs, which cannot be overloaded, and how does && still work?
answer
- static methods with a special name
- comparison operators travel in pairs
- short-circuit operators are composed
- operator false decides the shortcut
basics
~20 sOperators are public static members taking the declaring type; ==/!=, </>, <=/>= and true/false must be paired (CS0216). =, &&, ||, ?:, the cast (T)x and a[i] cannot be overloaded; && and || come from & or | plus operator true and false.
solid answer
~50 sAn operator is a `public static` member, and at least one parameter must be the declaring type, otherwise CS0558 or CS0563. Comparison operators come in pairs, `==` with `!=`, `<` with `>`, `<=` with `>=`, and so do `true` with `false`; leaving one out is CS0216. Assignment, member access, `?:`, `??`, `is`, `as`, `new` and `&&`/`||` cannot be overloaded, and trying `operator &&` fails to parse (CS1020). Casts are customised through conversion operators and `a[i]` through indexers. `&&` still works: `x && y` is evaluated as `T.false(x) ? x : T.&(x, y)`, so declaring `&`, `operator true` and `operator false` gives short-circuiting for free; without true and false it is CS0218. Since C# 11, `+`, `-`, `*`, `/`, `++`, `--` and explicit conversions may also have a `checked` form, and since C# 14 compound assignments such as `+=` can be overloaded as instance operators.
code
csharp · 16 linesvar frost = new Alarm("frost", Raised: false);
var gale = new Alarm("gale", Raised: true);
Console.WriteLine((frost && Read(gale)).Name);
Console.WriteLine((gale && Read(frost)).Name);
if (gale) Console.WriteLine("gale is raised");
static Alarm Read(Alarm a) { Console.WriteLine($" evaluated {a.Name}"); return a; }
readonly record struct Alarm(string Name, bool Raised)
{
public static Alarm operator &(Alarm a, Alarm b) => new($"{a.Name}&{b.Name}", a.Raised && b.Raised);
public static Alarm operator |(Alarm a, Alarm b) => new($"{a.Name}|{b.Name}", a.Raised || b.Raised);
public static bool operator true(Alarm a) => a.Raised;
public static bool operator false(Alarm a) => !a.Raised;
}go deeper
Recall that operators are public static methods on the type and that comparison operators must be declared in matching pairs.
Explain which operators cannot be overloaded and what to declare instead: indexers for a[i], conversion operators for casts, & with true and false for &&.
Walk through the rewrite x && y to T.false(x) ? x : T.&(x, y), the CS0217 and CS0218 requirements, and when checked operators are selected.
Judge which operators a shared domain type should expose at all, since a surprising operator is a permanent API commitment for every caller.
## What an operator declaration is An **overloaded operator** is a method with a special metadata name, such as `op_Addition` or `op_LessThan`, that the compiler calls when it sees the operator symbol with operands of your type. For a `Celsius` struct in a units library, the classic declarations look like this: ```csharp public static Celsius operator +(Celsius a, CelsiusDelta d) => new(a.Degrees + d.Degrees); public static bool operator <(Celsius a, Celsius b) => a.Degrees < b.Degrees; public static bool operator >(Celsius a, Celsius b) => a.Degrees > b.Degrees; ``` The compiler enforces the shape: - The operator must be `public` and, except for the C# 14 compound assignment and instance increment forms, `static`; otherwise CS0558. - A binary operator needs at least one parameter of the declaring type (or its nullable form), otherwise CS0563; a unary operator's parameter must be that type (CS0562). - A static class cannot declare operators (CS0715). - An operator other than the C# 14 compound assignment and instance increment forms cannot return `void` (CS0590). ## Operators that must come in pairs Some operators are only meaningful together, so declaring one without its partner is error **CS0216**, "The operator '...' requires a matching operator '...' to also be defined": | Declared | Must also declare | |---|---| | `operator ==` | `operator !=` | | `operator <` | `operator >` | | `operator <=` | `operator >=` | | `operator true` | `operator false` | The compiler never derives one from the other, so `<` does not give you `>=`. Overloading `==` also brings in `Equals` and `GetHashCode`, which belong to the lesson on equality. ## What cannot be overloaded The C# reference lists the operators a type can never redefine, and the replacement for each: - `&&` and `||`: declare `&` or `|` plus `operator true` and `operator false`. Writing `operator &&` is a syntax error, CS1020 "Overloadable binary operator expected", in the .NET 10 SDK. - `a[i]` and `a?[i]`: declare an indexer instead. - The cast `(T)x`: declare a user-defined conversion operator instead. - `=`, `.`, `?.`, `?:`, `??`, `??=`, `..`, `=>`, `is`, `as`, `typeof`, `sizeof`, `new`, `default`, `nameof`, `checked`, `unchecked`, `await`, `switch`, `with` and a few more: no alternative. Compound assignments such as `+=` were on that list until C# 14. Before C# 14, `x += y` always used the binary `+` and assigned the result; C# 14 lets a type declare an instance `operator +=` as well. ## How && and || reach your operators The language rewrites the short-circuit operators in terms of the ones you may declare: 1. `x && y` becomes `T.false(x) ? x : T.&(x, y)`. If `operator false` says `x` is definitely false, the result is `x` and `y` is **never evaluated**. 2. `x || y` becomes `T.true(x) ? x : T.|(x, y)`. 3. For this rewrite to apply, the `&` or `|` operator must take two parameters of the declaring type and return it (CS0217), and the type must declare `operator true` and `operator false` (CS0218). The code example below shows the `Alarm` type: `frost && Read(gale)` prints `frost` without evaluating `gale`, while `gale && Read(frost)` evaluates both and calls `&`. `operator true` also lets the type appear in an `if` condition. ## Checked operators Since C# 11 a type can declare a **checked** variant of `+`, `-`, `*`, `/`, unary `-`, `++`, `--` and explicit conversions, such as `public static Tally operator checked +(Tally x, Tally y)`. Inside a checked context the compiler calls the checked form; elsewhere it calls the regular one. A checked operator without its regular partner is CS9025, and `==` or `%` cannot be checked (CS9023). ## Keeping operators unsurprising - Overload an operator only when its meaning is obvious; adding two absolute temperatures is questionable, adding a temperature and a delta is not. - Keep the paired operators consistent with each other and with `CompareTo` when the type also implements `IComparable<T>`. - The analyzer rule CA2225, not enabled by default in .NET 10, asks for named alternates such as `Add` or `CompareTo` for languages without operators. In an interview, the details that separate a strong answer are the **pairing rule** with its CS0216 error, the short list of operators that can never be redefined, and the rewrite that turns `&&` into `operator false` plus `&`. Being able to say why `&&` cannot be overloaded directly, namely that a method call would always evaluate both arguments, shows that the candidate understands what short-circuiting requires.
- Why does the compiler insist on `operator >` when the code only needs `<`?C# requires `<` and `>` to be declared together, and `<=` with `>=`; omitting the partner is CS0216. The compiler never derives a missing operator from its partner, so a common approach is to implement all four on top of one `CompareTo` method.
- How does the compiler choose between `operator +` and `operator checked +` on the same type?Inside a checked context, created by a `checked` expression or block or by the `CheckForOverflowUnderflow` project setting, the checked form is used; everywhere else the regular form is. The checked variant needs the regular one declared beside it (CS9025), and only arithmetic operators, increments and explicit conversions have checked forms.
- What does CS0217 tell you about an `&` operator meant to support `&&`?For short-circuit use, the user-defined `&` (or `|`) must take two parameters of the declaring type and return that same type. An `&` that returns `bool` or takes a different operand type can still be called directly, but `&&` cannot be rewritten through it, so the compiler reports CS0217.
- Believing a type can declare operator && or operator || directly.
- Assuming the compiler derives operator > from operator <.
- Declaring an operator as an instance method, as for an ordinary member.
- Claiming += could always be overloaded independently of +.
- Saying && on a user type always evaluates both operands.
Assumes C# 14 on .NET 10; compound assignment operators became overloadable in C# 14, and checked operators date from C# 11.