When you overload operator == on a C# class, what does the compiler require, and why can a null check inside it overflow the stack?
answer
- operators come in pairs
- CS0216, CS0660, CS0661
- == inside == calls itself
- is null skips user operators
basics
~20 sC# requires operator != beside operator == (error CS0216) and warns if Equals or GetHashCode is not overridden. Writing left == null inside the operator calls the same operator again, recursing until the stack overflows; use is null instead.
solid answer
~40 sDeclaring `operator ==` without `operator !=` is error CS0216, and declaring either without overriding `Equals` and `GetHashCode` gives warnings CS0660 and CS0661, so the usual design is all four members delegating to one `Equals`. Inside the operator, the operands are typed as the class itself, so `if (left == null)` is resolved to the very operator being written: it calls itself until the runtime prints "Stack overflow." and terminates the process. `left is null` or `ReferenceEquals(left, null)` never invokes a user-defined `==`. And because operators bind to static types, the overload is skipped whenever operands are typed `object`, a base type, or a generic `T` constrained to `class`.
code
csharp · 22 linesvar a = new Sku("SKU-42");
var b = new Sku("SKU-42");
Console.WriteLine(a == b); // True: Sku's operator ==
Console.WriteLine((object)a == (object)b); // False: object's reference test
Console.WriteLine(Same(a, b)); // False: generic code never sees Sku's ==
Console.WriteLine(a == null); // False, no recursion
static bool Same<T>(T x, T y) where T : class => x == y;
sealed class Sku(string code) : IEquatable<Sku>
{
public string Code { get; } = code;
public bool Equals(Sku? other) => other is not null && Code == other.Code;
public override bool Equals(object? obj) => Equals(obj as Sku);
public override int GetHashCode() => Code.GetHashCode();
public static bool operator ==(Sku? left, Sku? right) =>
left is null ? right is null : left.Equals(right);
public static bool operator !=(Sku? left, Sku? right) => !(left == right);
}go deeper
Recall that == and != are overloaded as a pair and that a class with == should also override Equals and GetHashCode so all comparisons agree.
Explain CS0216, CS0660 and CS0661, write the four members delegating to one Equals, and show why left == null inside the operator recurses while is null does not.
Point out where an overload is silently skipped, such as object-typed APIs, base-class variables and generic code, and how a recursive operator takes the whole process down on first use.
Set the rule for when a class may overload == at all: immutable value-like types yes, identity-tracked entities no, and records preferred when the type can be one.
## What overloading == means in C# A **user-defined operator** is a `public static` method with the `operator` keyword. Declaring `public static bool operator ==(Sku? left, Sku? right)` tells the compiler to call that method whenever both operands are statically typed `Sku` (or convertible to it). Without it, `==` on a class is the predefined **reference comparison**, `True` only when both variables point to one object. General operator overloading, conversions and compound assignment are covered with operators and casts; this lesson is about the equality pair and how it must line up with `Equals`. ## What the compiler enforces Three diagnostics guard the pair: | Situation | Diagnostic | Severity | |---|---|---| | `operator ==` declared without `operator !=` (or the reverse) | CS0216: "The operator 'Sku.operator ==(Sku?, Sku?)' requires a matching operator '!=' to also be defined" | error | | `==` or `!=` declared, `Equals(object)` not overridden | CS0660 | warning | | `==` or `!=` declared, `GetHashCode` not overridden | CS0661 | warning | The warnings exist because collections, LINQ and `object.Equals` never call your operator; they call `Equals` and `GetHashCode`. If `==` says equal and `Equals` says not, the same two objects behave differently depending on who compares them. The robust layout is: 1. `Equals(Sku? other)` holds the real comparison. 2. `Equals(object? obj)` forwards to it. 3. `GetHashCode` hashes the same members. 4. `operator ==` handles `null` with patterns, then calls `Equals`; `operator !=` returns `!(left == right)`. ## The recursion trap Inside `operator ==(Sku? left, Sku? right)`, both parameters are typed `Sku?`. A null check written as `left == null` is therefore an expression of type `Sku? == null`, and overload resolution picks the best candidate: the operator you are writing. The method calls itself with the same arguments, forever. The compiler gives no warning. At run time the thread exhausts its stack; the snippet tried for this lesson printed "Stack overflow." with the repeated frame and the process exited, so the bug takes the whole service down on the first comparison, and .NET's design guidelines say not to catch `StackOverflowException` at all. The safe forms never reach a user-defined operator: - **`left is null`**: the C# documentation guarantees that matching against `null` does not invoke a user-overloaded `==` or `!=`. - **`object.ReferenceEquals(left, null)`**: always an identity test. - **`(object)left == null`**: casting to `object` makes the compiler choose reference equality. ## The overload is static, so some callers never see it Because operators are bound at compile time from the **static** types, your overload is silently bypassed in several places: - Operands typed `object` or an interface: `(object)a == (object)b` compares references. - A **base class** that does not declare the operator: a variable typed as the base compares references. - **Generic code**: in `static bool Same<T>(T x, T y) where T : class => x == y`, the compiler only knows `T` is a reference type, so `==` is reference equality even when the type argument is `Sku`. Without the `class` constraint the line does not compile at all (CS0019). Generic code that needs value equality calls `EqualityComparer<T>.Default.Equals(x, y)` or `x.Equals(y)`. ## Checking the four members together A short test catches most mistakes in a hand-written equality pair: - `a == b` and `a.Equals(b)` agree for every pair of test objects, including pairs where either side is `null`. - `a != b` is exactly `!(a == b)`. - Whenever `a.Equals(b)` is `true`, `a.GetHashCode() == b.GetHashCode()`. - No comparison on the class's own type appears inside its operators; null checks use `is null`. ## When to overload == at all - **Immutable, value-like classes** (a money amount, a SKU code) are good candidates; readers expect `==` to compare values for them, as it does for `string`. - **Mutable entities** that are tracked by identity usually should not overload it, because code that tests "is this the same instance?" with `==` changes meaning. - **Records** already generate `==`, `!=`, `Equals` and `GetHashCode` together; that generated code is covered with records. - **Structs** get no `==` until they declare it (CS0019 otherwise), so the same pairing rules apply to them.
- Does `if (left is null)` inside `operator ==` behave differently from `if ((object)left == null)`?No. Both test the reference without calling a user-defined operator: the documentation guarantees `is null` never invokes an overloaded `==`, and the cast to `object` makes the compiler choose reference equality. `is null` is the clearer form and also works where a cast would read awkwardly.
- How should a generic method compare two `T` values so a type's value equality is honoured?Call `EqualityComparer<T>.Default.Equals(x, y)`. It uses `IEquatable<T>.Equals` or the `Equals(object)` override, both of which a well-built type keeps in line with its `==`. Writing `x == y` either fails to compile (CS0019, unconstrained `T`) or, with a `class` constraint, compares references and ignores the overload.
- The compiler derives operator != automatically from operator ==
- Overloading == is enough; Dictionary and HashSet will use the operator
- Writing left == null inside operator == is the normal null check
- A generic method constrained to class uses the type argument's overloaded ==
- The compiler warns about the infinite recursion before it runs