skip to content

In a C# chat dispatcher, why does `if (message == null) return;` drop blank messages once Message overloads operator ==, while `is null` does not?

level: seniorimportance: should knowfreq 48%

answer

  1. operators bind at compile time
  2. a constant pattern, not an operator call
  3. ldnull and ceq in the IL
  4. is not null bypasses != too

basics

~20 s

message == null calls Message's user-defined operator ==, whose rule treats a blank message as equal to null, so the guard returns early. message is null compiles to a plain reference comparison and never calls a user-defined operator.

solid answer

~40 s

Operators are chosen when the caller is compiled: with `message` typed `Message`, `message == null` binds to the user-defined `operator ==(Message?, Message?)`, and that operator says a blank message equals `null`, so the guard drops it. `message is null` is a **null constant pattern**; the C# reference guarantees it never invokes a user-overloaded `==` or `!=`, and the SDK emits only `ldnull` and `ceq` for it. `is not null` likewise bypasses `!=`. So `is null` asks "is there an object at all?", while `== null` asks whatever the type's author decided equality means. Fix the guard with `if (message is null) return;` and test blankness separately. On an `int?`, `is null` tests for no value; on an unconstrained generic `T` it compiles and is `false` for a value-type argument.

code

csharp · 28 lines
csharp
Message? empty = new Message("");
Message? missing = null;

Console.WriteLine($"empty == null      -> {empty == null}");
Console.WriteLine($"empty is null      -> {empty is null}");
Console.WriteLine($"missing == null    -> {missing == null}");
Console.WriteLine($"missing is null    -> {missing is null}");
Console.WriteLine($"empty != null      -> {empty != null}");
Console.WriteLine($"empty is not null  -> {empty is not null}");

class Message(string body)
{
    public string Body { get; } = body;

    // Equality rule: a blank message counts as equal to null.
    public static bool operator ==(Message? left, Message? right)
    {
        Console.WriteLine("  (operator == ran)");
        bool leftBlank = left is null || left.Body.Length == 0;
        bool rightBlank = right is null || right.Body.Length == 0;
        if (leftBlank || rightBlank) return leftBlank && rightBlank;
        return left!.Body == right!.Body;
    }

    public static bool operator !=(Message? left, Message? right) => !(left == right);
    public override bool Equals(object? obj) => obj is Message other && this == other;
    public override int GetHashCode() => Body.GetHashCode();
}

go deeper

for a junior

Recall that is null and is not null are the null checks that never run the type's own code, while == null can run an operator the type's author wrote.

for a middle

Explain that operator overloads bind from static types at compile time, so == null on a Message variable calls Message's operator, while is null is a constant pattern that never does.

for a senior

Diagnose a guard that drops valid objects by finding an overloaded == on the type, prove it with a log line or the IL, and fix the guard with is null plus an explicit domain check.

for a principal

Weigh a team rule of is null for null checks against types whose contract defines equality with null, and decide how reviews treat an operator == that can return true for a non-null object.

## Where the blank messages went A `Message` class gained an equality rule: two messages are equal when their bodies match, and a message with an empty body counts as equal to `null`. The author implemented it as `operator ==` and `operator !=`. Nobody touched the dispatcher, whose first line is: ```csharp if (message == null) return; ``` After the change, blank messages stop reaching the handlers. Nothing threw; the guard simply started returning early for them. ## Why == reaches the user-defined operator Operator overloads are **static methods chosen by overload resolution when the calling code is compiled**, using the operands' **static types**: - `message` is declared as `Message?`, and `null` converts to `Message?`, so `operator ==(Message?, Message?)` is applicable and is chosen over the built-in reference comparison. - At run time that operator receives the blank message and `null`, applies its rule and returns `true`. - The choice depends on the declared type, not the object: if `message` were declared as `object`, `message == null` would be the built-in reference comparison, because `object` declares no `operator ==`. So `== null` means "equal to null **according to this type**", and a type may define that however it likes. ## What is null compiles to `message is null` is a **constant pattern** whose constant is `null`. The C# reference states that when matching against `null`, "the compiler guarantees that no user-overloaded `==` or `!=` operator is invoked". The compiled code confirms it. For a method `IsNull(Message? m) => m is null` the SDK emitted `ldarg.0, ldnull, ceq`; for `EqNull(Message? m) => m == null` it emitted `ldarg.0, ldnull, call op_Equality`. | Check | Calls a user-defined operator? | Meaning | |---|---|---| | `message == null` | yes, if `Message` declares `==` | the type's own equality with null | | `message != null` | yes, if `Message` declares `!=` | the type's own inequality | | `message is null` | never | no object at all | | `message is not null` | never | an object exists | | `(object)message == null` | no; `object` declares no operator | reference comparison | | `ReferenceEquals(message, null)` | no | reference comparison, spelled out | The code-style rule IDE0041 ("Use 'is null' check") prefers the pattern form over a `ReferenceEquals` call. ## is null on other kinds of operand - On a **nullable value type** such as `int?`, `x is null` is true when the value is absent, the same answer `x.HasValue` gives in reverse. - In a **generic method with an unconstrained `T`**, `value is null` compiles. For a value-type argument it is simply `false`; the SDK printed `False` for `IsMissing(0)`. - On a **non-nullable value type** known at compile time, such as an `int` local, `count is null` is error CS0037: "Cannot convert null to 'int' because it is a non-nullable value type". ## When == null is the intended test Sometimes the equality rule is the point. A type may deliberately define equality with `null`, as some game-engine object types do for objects the engine has already destroyed; there, `is null` sees a live reference and misses the engine's rule. These cases are the exception, and a reader cannot tell them apart from a bug without reading the type. For ordinary domain types, a rule like "blank equals null" hides a separate question behind the null check. ## Fixing the dispatcher 1. Change the guard to `if (message is null) return;` so only a missing object is dropped. 2. Give blankness its own name, for example an `IsBlank` property, and decide in the dispatcher what blank messages should do. 3. Reconsider the operator: equality that makes a real object equal to `null` surprises every caller that writes `== null`, including code in other assemblies. 4. Search for other `== null` and `!= null` checks on the type; each one now runs the custom rule.

  • In C#, does `message is not null` also bypass an overloaded `!=` operator?
    Yes. `is not null` is the negated null constant pattern, so like `is null` it compiles to a direct reference check and never calls a user-defined `!=`. In the dispatcher snippet `empty != null` printed False through the operator, while `empty is not null` printed True.
  • Why does `(object)message == null` also avoid Message's operator ==?
    Operator overloads are chosen from the operands' static types when the caller is compiled. After the cast the left operand is `object`, which declares no `operator ==`, so the built-in reference comparison applies. `ReferenceEquals(message, null)` is the explicit spelling; `is null` says the same thing more briefly.
  • When is `== null` the check a C# developer actually wants?
    When the type's documented contract makes some live objects equal to `null` and you want that rule; Unity's engine objects, for instance, overload `==` so a destroyed object compares equal to `null`, and `is null` would miss it. Outside such documented cases, prefer `is null` plus a named check for the domain condition.

  • is null and == null always compile to the same check
  • is null calls the type's Equals method under the hood
  • An overloaded == is chosen at run time from the object's actual type
  • is null cannot be used on a type that overloads operator ==
  • is not null still calls the type's overloaded != operator