skip to content

A C# cleanup rewrites `if (avatar != null) avatar.Render();` as `avatar?.Render();`; why does that change behaviour when Avatar's `==` treats a disposed instance as null?

level: seniorimportance: should knowfreq 40%

answer

  1. ?. is not shorthand for != null
  2. null-aware operators cannot be overloaded
  3. the old guard ran the type's !=
  4. ?? and ??= keep a disposed object

basics

~20 s

The old guard calls Avatar's overloaded != operator, which reports a disposed avatar as null, so Render is skipped. ?. only checks whether the reference is null, so the rewrite calls Render on the disposed avatar. ?? and ??= behave the same way.

solid answer

~50 s

`x?.M()` is often read as shorthand for `if (x != null) x.M()`, but `?.` is not defined through `!=`. `?.`, `?[]`, `??` and `??=` evaluate their left operand once and test whether that reference is null; all four are on C#'s list of operators that cannot be overloaded, so no type can redirect them to its own `operator ==`. On a type whose `==`/`!=` reports a disposed instance as null, the rewrite changes which objects pass: `avatar?.Render()` calls into the disposed avatar, `avatar ?? placeholder` keeps it, and `_avatar ??= Load()` never reloads it. The rewrite is behaviour-preserving only when the operand's static type declares no `operator ==`. On such types keep the explicit guard, or ask the real question by name: `if (avatar is null || avatar.IsDisposed) return;` and then call members with a plain `.`.

code

csharp · 28 lines
csharp
Avatar? avatar = new Avatar(isDisposed: true);
var placeholder = new Avatar(isDisposed: false);

if (avatar != null) Console.WriteLine(avatar.Render()); // skipped: the overloaded != says "null"
Console.WriteLine(avatar?.Render() ?? "skipped");       // ?. tests the reference, so Render runs
Console.WriteLine((avatar ?? placeholder).IsDisposed);  // True: ?? kept the disposed avatar
avatar ??= Load();                                      // Load is not called
Console.WriteLine(avatar.IsDisposed);                   // True

static Avatar Load()
{
    Console.WriteLine("Load called");
    return new Avatar(isDisposed: false);
}

class Avatar(bool isDisposed)
{
    public bool IsDisposed { get; } = isDisposed;
    public string Render() => IsDisposed ? "rendering a disposed avatar" : "ok";

    // A disposed avatar compares equal to null.
    public static bool operator ==(Avatar? left, Avatar? right) =>
        (left is null || left.IsDisposed) && (right is null || right.IsDisposed)
        || ReferenceEquals(left, right);
    public static bool operator !=(Avatar? left, Avatar? right) => !(left == right);
    public override bool Equals(object? obj) => obj is Avatar other && this == other;
    public override int GetHashCode() => IsDisposed ? 0 : base.GetHashCode();
}

go deeper

for a junior

Recall that ?. and ?? check only for a null reference and that a class cannot change what they do.

for a middle

Explain why if (x != null) x.M() and x?.M() can disagree: the first calls the type's !=, the second tests the reference.

for a senior

Diagnose a disposed object that still receives calls through ?. after failing a == null guard, and refuse null-propagation refactors on types that overload ==.

for a principal

Set the team's rule: never make live objects equal null; expose a named validity property so null-aware operators and == agree.

## The refactor that looks safe IDE suggestions and cleanup passes turn explicit null guards into the null-aware operators: | Before | After | |---|---| | `if (avatar != null) avatar.Render();` | `avatar?.Render();` | | `avatar != null ? avatar : placeholder` | `avatar ?? placeholder` | | `if (_avatar == null) _avatar = Load();` | `_avatar ??= Load();` | On most types each pair means the same thing. It stops being true when the type **overloads `==` and `!=`** so that some live objects compare equal to null, typically an object that was disposed, destroyed or invalidated while a reference to it is still held: ```csharp public static bool operator ==(Avatar? left, Avatar? right) => (left is null || left.IsDisposed) && (right is null || right.IsDisposed) || ReferenceEquals(left, right); ``` ## What each side asks The left column goes through overload resolution: `avatar != null` binds to `Avatar`'s `operator !=`, and the type's author decides that a disposed avatar is "null". The right column never does. For a disposed avatar that is still referenced: | Form | Result | Decided by | |---|---|---| | `if (avatar != null) avatar.Render();` | `Render` is skipped | the overloaded `!=` | | `avatar?.Render();` | `Render` runs on the disposed object | the reference | | `avatar != null ? avatar : placeholder` | `placeholder` | the overloaded `!=` | | `avatar ?? placeholder` | the disposed `avatar` | the reference | | `if (_avatar == null) _avatar = Load();` | `Load` runs | the overloaded `==` | | `_avatar ??= Load();` | `Load` is not called | the reference | ## Why the operators cannot follow the type The C# reference lists `x?.y`, `a?[i]`, `x ?? y` and `??=` among the operators that **cannot be overloaded**, with no alternative. Their meaning is fixed by the language: evaluate the left operand once, test it for null (for a `Nullable<T>`, test `HasValue`), and short-circuit. Overloading `==`, overriding `Equals` or declaring `operator true`/`false` changes none of that. So a type that wants a custom notion of "null" gets it only from code that spells `==` or `!=`; every null-aware operator, and the `is null` pattern covered with type tests, still sees the plain reference. Unity's engine objects are the best-known type built this way, and Unity's documentation warns against using `?.` and `??` on them for exactly this reason. ## The other difference: one read instead of two `if (Current != null) Current.Render();` reads `Current` twice when it is set; `Current?.Render();` reads it once. With a property getter or a field that another thread can clear, the rewrite also changes behaviour, here in the safe direction: the checked value is the one that is used. That is why the rewrite is usually right, and why it is easy to approve without looking at the operand's type. ## What to take into code review 1. Before accepting the rewrite on a type you do not control, check whether the type or a base class declares `operator ==`. If it does, the rewrite changes which objects pass. 2. Do not mix the two families on one variable. `if (avatar == null) return;` followed later by `avatar?.Render()` answers two different questions, and that inconsistency is the usual bug report: "after the avatar is disposed we still see render calls, although we check for null". 3. Ask the question by name: `if (avatar is null || avatar.IsDisposed) return;`, then call members with a plain `.`. 4. In your own types, do not make live objects equal null. Expose a named property such as `IsDisposed`, so every null-aware operator keeps meaning what it says. Designing `==` itself, together with `Equals` and `GetHashCode`, belongs to equality and hashing.

  • When is rewriting `if (x != null) x.M();` as `x?.M();` behaviour-preserving?
    When the static type of `x`, including its base classes, declares no `operator ==` or `operator !=`: then `!=` against null is a plain reference test and both forms ask the same question. The one remaining difference is that `x?.M()` reads `x` once, so a property getter or a field another thread clears is no longer read twice.
  • A type you do not control overloads `==` to report destroyed objects as null; how should a guard be written?
    Ask both questions explicitly and once: `if (obj is null || obj.IsDestroyed) return;` (or the type's own `==` if that is its documented contract), then call members with a plain `.`. Do not follow that guard with `?.` or `??` on the same variable, because they ignore the type's rule.

  • x?.M() is compiled as if (x != null) x.M(), so it uses the type's != operator
  • Rewriting if (x != null) x.M() as x?.M() never changes behaviour
  • A type can overload ?? or ?. to apply its own null rule
  • _x ??= Load() reloads an object whose overloaded == reports it as null
  • Mixing == null guards and ?. calls on the same variable is harmless