skip to content

In C#, how does `payload as TextMessage` followed by a null check differ from `payload is TextMessage text`, and where will as not compile?

level: middleimportance: must knowfreq 66%

answer

  1. same type test underneath
  2. as always yields a value
  3. the target must accept null
  4. CS0077 on a value type
  5. pattern variable assigned only when true

basics

~20 s

The as form and the is pattern run the same run-time type test, but as yields null on failure, needs a separate null check and rejects non-nullable value types (CS0077). The is pattern tests and declares in one step.

solid answer

~40 s

Underneath they are the same type test: the SDK emits one `isinst` instruction for `payload as TextMessage` and for `payload is TextMessage text`. The difference is what you get back. `as` always produces a value, the converted reference or `null`, so you declare a `TextMessage?` variable, write a separate `!= null` check, and that variable stays in scope holding `null` when the test failed. `is` with a declaration pattern returns `bool` and declares `text`, definitely assigned only where the test was true. `as` targets only reference types and nullable value types: `payload as int` is error CS0077, so you write `payload as int?` or, better, `payload is int receiptId`. Neither form uses user-defined conversions. `as` still fits when a nullable result is what you want, as in `(payload as TextMessage)?.Body ?? "(none)"`.

code

csharp · 22 lines
csharp
object?[] payloads = [new TextMessage("hi"), 4711, null];

foreach (object? payload in payloads)
{
    // as: the variable exists whether or not the conversion worked
    TextMessage? asText = payload as TextMessage;
    int? asReceipt = payload as int?;          // payload as int would be CS0077
    Console.WriteLine($"as   -> text: {asText?.Body ?? "(null)"}, receipt: {asReceipt?.ToString() ?? "(null)"}");

    // is: the variable is assigned only where the test is true
    if (payload is TextMessage text)
        Console.WriteLine($"is   -> text: {text.Body}");
    else if (payload is int receiptId)
        Console.WriteLine($"is   -> receipt: {receiptId}");
    else
        Console.WriteLine("is   -> no match (null never matches a type)");
}

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

go deeper

for a junior

Recall that as returns null instead of throwing, that its result must be checked for null, and that is with a declaration pattern does the test and declares the variable in one expression.

for a middle

Explain that both forms compile to the same type test, why as cannot target int (CS0077), and why a null from as cannot tell a null payload from one of the wrong type.

for a senior

In review, replace as-plus-null-check and is-plus-cast chains with declaration patterns, keep as where a nullable result feeds ?. or ??, and treat CS8121 and CS0184 as reports of dead branches.

for a principal

Decide whether the team enforces IDE0019 and IDE0020 in new code and how hard to push existing files, weighing review churn against fewer double casts and unchecked nullable variables.

## Two spellings of one type test The C# reference defines `E as T` as producing the same result as `E is T ? (T)(E) : (T)null`, except that `E` is evaluated only once. So `as` is a type test whose failure value is `null`. A declaration pattern, `E is T x`, is the same type test whose failure value is `false`, with the converted value placed in `x` on success. The compiled code shows how close they are. For both of these methods the SDK emitted a single `isinst TextMessage` instruction followed by a branch: ```csharp string ViaIs(object o) => o is TextMessage t ? t.Body : ""; string ViaAs(object o) { var t = o as TextMessage; return t != null ? t.Body : ""; } ``` Choosing between them is therefore about **what the code around the test looks like**, not about speed. ## What each form gives you | | `payload as TextMessage` | `payload is TextMessage text` | |---|---|---| | Result | a `TextMessage?` value, `null` on failure | a `bool`; `text` assigned on success | | Null input | `null` | `false` | | Wrong type | `null` | `false` | | Value-type target | only nullable, as in `as int?` | any, as in `is int id` | | Follow-up | a separate null check | none; the `if` already tested | | Variable after failure | in scope, holding `null` | in scope, not definitely assigned | Two consequences matter in review: - A `null` from `as` cannot tell a null payload from a payload of the wrong type. Both produce `null`. - The null check after `as` is an ordinary `!=` expression, so it binds to a user-defined `!=` if the target type declares one. The pattern form has no separate comparison to get wrong. ## Where as does not compile Because `as` must be able to return `null`, the target must be a type that can hold `null`: 1. `payload as int` is error CS0077: "The as operator must be used with a reference type or nullable type ('int' is a non-nullable value type)". `payload as int?` compiles and unboxes a boxed `int`. 2. When no reference, boxing, unboxing or nullable conversion exists, as from the sealed `ImageMessage` to the unrelated `TextMessage`, `img as TextMessage` is error CS0039. 3. The pattern form of the same impossible test, `img is TextMessage t`, is error CS8121, while the pattern-less `img is TextMessage` is only warning CS0184. ## Conversions both forms skip The C# reference says `as` considers **only reference, nullable, boxing and unboxing conversions**, and that declaration patterns don't consider user-defined conversions either. In practice: - An `implicit operator` or `explicit operator` declared on a class is never called by `as` or by `is`. - A boxed `long` does not come out of `as int?` or `is int`; there is no numeric conversion on unboxing. - To run a user-defined or numeric conversion you need an explicit cast, which throws `InvalidCastException` on a mismatch instead of returning `null`; casts are covered in the lesson on operators and conversions. ## When as is still the right tool - When the **nullable result itself** feeds the next expression: `(payload as TextMessage)?.Body ?? "(no text)"` reads in one line. - When a nullable variable has to outlive the test, for example to pass along "maybe a `TextMessage`" to another method. - In older code that must compile with a C# version before 7.0, which had no declaration patterns. Everywhere else, a declaration pattern is shorter and lets the compiler prove the variable is assigned where it is used. ## Modernising old type tests The .NET code-style rules cover both legacy shapes: IDE0019 ("Use pattern matching to avoid 'as' followed by a 'null' check") and IDE0020 ("Use pattern matching to avoid 'is' check followed by a cast (with variable)"). The rewrite is mechanical: 1. Find `var x = e as T; if (x != null) { ... }` and replace it with `if (e is T x) { ... }`. 2. Find `if (e is T) { var x = (T)e; ... }`, which tests the type twice, and replace it the same way. 3. Check whether code after the `if` read `x`; with the pattern form it is no longer definitely assigned there, and the compiler will report CS0165 until you restructure. 4. Keep `as` where the code really wants a nullable value.

  • In C#, is `payload as TextMessage` plus a null check faster than `payload is TextMessage text`?
    No. The SDK emits the same single `isinst` instruction for both. The slower legacy form is `payload is TextMessage` followed by `(TextMessage)payload`, which checks the type twice, once for the test and again for the cast. Choosing between `as` and `is` is about scope, null handling and readability, not speed.
  • In C#, how do you get a nullable receipt id out of an object payload with as?
    `payload as int?` compiles because `int?` can hold `null`: it yields the value when `payload` holds a boxed `int`, and `null` for anything else, including a boxed `long`. `payload is int receiptId` does the same test without the nullable wrapper and gives a plain `int` inside the `if`.

Asking with as is like signing for a parcel that may be an empty envelope: you always walk away holding something and must open it to check. The is pattern is a door that opens only when the right parcel is there and hands it to you on the other side.

  • as is faster than is because it performs only one type check
  • payload as int returns 0 when payload is not a boxed int
  • as calls a class's implicit conversion operator when one exists
  • as throws InvalidCastException when the types do not match
  • A null result from as proves the payload had the wrong type