skip to content

In C#, why is `receipt is 42` false when the object receipt holds a boxed 42L, and what do `is var x` and `is var _` match?

level: middleimportance: should knowfreq 38%

answer

  1. the constant has a type too
  2. a boxed long is not a boxed int
  3. object input: type and value must agree
  4. var matches null as well
  5. a bare _ reads as a type name

basics

~20 s

For an object input, the constant pattern 42 matches only a boxed int equal to 42; a boxed long never does, because no numeric conversion runs. The var pattern matches every value, null included, and var _ matches anything without naming it.

solid answer

~50 s

A constant pattern compares the input with a constant by the language's built-in equality rules, not by a user-defined `==`. When the input's static type is integral, as with `long total`, the constant is converted at compile time and `total is 42` is a numeric comparison. When the input is `object`, the constant keeps its own type, `int`, so `receipt is 42` matches only a boxed `int` equal to 42; the C# 7.0 pattern design describes this case as `object.Equals(e, c)`, and a boxed `long` is never equal to a boxed `int`. Write `receipt is 42L` instead. String constants compare content, and `reading is double.NaN` is true where `reading == double.NaN` is false. The **var pattern** `is var v` matches everything, `null` included, and gives `v` the input's static type; `is var _` matches anything without a name, while a bare `is _` reads `_` as a type name (CS0246).

code

csharp · 14 lines
csharp
object receipt = 42L;                 // a boxed long, not a boxed int
object ping = "ping";
object? nothing = null;
double reading = double.NaN;
long total = 42;

Console.WriteLine($"receipt is 42        -> {receipt is 42}");
Console.WriteLine($"receipt is 42L       -> {receipt is 42L}");
Console.WriteLine($"total is 42          -> {total is 42}");
Console.WriteLine($"ping is \"ping\"       -> {ping is "ping"}");
Console.WriteLine($"nothing is var v     -> {nothing is var v}, v is null: {v is null}");
Console.WriteLine($"nothing is object    -> {nothing is object}");
Console.WriteLine($"reading == NaN       -> {reading == double.NaN}");
Console.WriteLine($"reading is NaN       -> {reading is double.NaN}");

go deeper

for a junior

Recall that is 0, is "ping" and is null are constant patterns, and that is var x captures the value whatever it is, null included.

for a middle

Explain how the constant is compared: converted to an integral input type, or matched by both type and value against an object input, which is why a boxed long fails is 42.

for a senior

Spot boxed-type mismatches in routing code that receives object payloads, and use typed constants or type patterns so an id stored as long still routes instead of falling through.

for a principal

Decide whether routing raw object payloads by constant patterns is acceptable at a service boundary, or whether payloads are normalised to one numeric type before dispatch.

## The constant pattern A **constant pattern** tests whether an input equals a compile-time constant. The C# reference lists what may appear: integer and floating-point literals, `char` and string literals, `true` and `false`, enum members, the name of a declared `const`, and `null`. In a dispatcher that receives `object` payloads it reads naturally: `payload is "ping"` for a keep-alive, `payload is 0` for an empty receipt, `payload is null` for nothing at all. The C# documentation says constant-pattern matching uses built-in language equality rules rather than a user-defined `==` operator. How it compares depends on the **static type of the input**. ## How the comparison is made The C# 7.0 pattern-matching design gives the rule: if both the input and the constant are of integral types, the pattern matches when `e == c` is true; otherwise it matches when `object.Equals(e, c)` is true. In practice: | Input declared as | Example | How it compares | Result | |---|---|---|---| | `long total = 42` | `total is 42` | constant converted to `long`, numeric `==` | true | | `object receipt = 42` (boxed `int`) | `receipt is 42` | type and value must agree | true | | `object receipt = 42L` (boxed `long`) | `receipt is 42` | a boxed `long` is not an `int` 42 | false | | `object receipt = 42L` | `receipt is 42L` | type and value agree | true | | `object ping` holding a built string | `ping is "ping"` | string content | true | | `string label` | `label is 42` | error CS0029 at compile time | — | The surprise is the third row. With an `object` input there is no static numeric type to convert the constant to, so `42` stays an `int`. At run time the payload is a boxed `long`, and `Int64.Equals` returns false for anything that is not a `long`. No numeric widening is applied to a boxed value; `(object)42L` and `(object)42` are different objects of different types. ## Fixing the receipt check When receipt ids sometimes arrive as `long`: 1. Match the type you actually receive: `receipt is 42L`, or `receipt is long id && id == 42`. 2. Or normalise at the boundary, converting every receipt id to one type before it is boxed into the payload. 3. Do not reach for a cast such as `(int)receipt`: unboxing a boxed `long` as `int` throws `InvalidCastException`. ## Floating point and strings - `reading is double.NaN` is **true** when `reading` is NaN, while `reading == double.NaN` is **false**, because IEEE 754 comparison makes NaN unequal to everything. The constant pattern follows `Equals`-style semantics, under which NaN equals NaN. Relational patterns are stricter: `reading is < double.NaN` is error CS8782, "Relational patterns may not be used for a floating-point NaN." - A string constant compares **content**: a string built at run time from a `char[]` still matches `"ping"`, even though it is a different object from the literal. ## The var pattern and the discard - `payload is var p` **always matches**, `null` included, and declares `p` with the input's **compile-time type** (`object` here). It is useful for capturing an intermediate value inside a larger condition, such as `payload is TextMessage text && text.Body.Trim() is var body && body.Length > 0`. - Because it always matches, `p` is definitely assigned afterwards; it may simply hold `null`. - `payload is var _` matches anything and binds nothing. - A bare `payload is _` is **not** a discard pattern. In an `is` expression the compiler reads `_` as a type name and, with no such type, reports CS0246, "The type or namespace name '_' could not be found". The C# reference states that the discard pattern can't be the pattern of an `is` expression or a `switch` statement; it belongs to switch expression arms. - To test "not null" use `is not null`; `is var x` never filters anything. ## What a constant pattern does not do - It does not use a user-defined `==` operator; the documentation describes built-in language equality rules. - It does not apply numeric conversions to a boxed value. - It does not compile when the input's static type can never hold the constant; `string label` with `is 42` is CS0029, "Cannot implicitly convert type 'int' to 'string'".

  • In C#, why does `long total = 42; total is 42` return true when the boxed case returns false?
    When the input's static type is integral, the compiler converts the constant to that type and compares numerically, so `42` becomes `42L`. With an `object` input there is no static numeric type to convert to, so the run-time value must be a boxed `int` equal to 42.
  • In C#, why does `payload is _` fail to compile, and what matches anything instead?
    In an `is` expression a bare `_` is not a discard pattern; the compiler reads it as a type name and reports CS0246 when no type named `_` exists. The documented way to match anything there is `is var _`. The discard pattern itself belongs to switch expression arms.

  • A constant pattern widens a boxed long to match an int constant
  • receipt is 42 on an object payload calls an overloaded == operator
  • The var pattern matches only non-null values
  • payload is _ is how to match anything in an is expression
  • x is double.NaN behaves exactly like x == double.NaN