In C#, what does `if (payload is TextMessage text)` test and assign when payload is an object, and which values make it match?
answer
- test and convert in one step
- run-time type, not static type
- subclasses and interfaces count
- null never matches a type
- assigned only where the test is true
basics
~20 sAn is test with a declaration pattern checks at run time that payload is non-null and holds a TextMessage or a subclass, then declares text holding that reference. Null and unrelated types never match, and no conversion operator runs.
solid answer
~50 s`payload is TextMessage text` is a **declaration pattern**. It evaluates `payload` once and matches when the value is non-null and its run-time type converts to `TextMessage` by identity, by an implicit reference conversion (a derived class such as `FormattedTextMessage`, or an implementing class when the pattern names an interface), by unboxing, or from a `Nullable<T>` that has a value. On a match it declares a new local `text` of static type `TextMessage` that refers to the same object: no copy is made. `null` never matches, and numeric and user-defined conversions are not considered, so a boxed `long` fails an `int` test. `text` is definitely assigned only where the `is` expression is true, such as inside the `if` block. If the static type of `payload` could never hold a `TextMessage`, the compiler rejects the test with CS8121.
code
csharp · 27 linesobject?[] payloads =
[
new TextMessage("hi"),
new FormattedTextMessage("**hi**", "markdown"),
new ImageMessage("cat.png"),
4711, // boxed int receipt id
4711L, // boxed long: not an int
null,
];
foreach (object? payload in payloads)
Console.WriteLine(Route(payload));
static string Route(object? payload)
{
if (payload is TextMessage text)
return $"text: {text.Body} ({text.GetType().Name})";
if (payload is ImageMessage image)
return $"image: {image.FileName}";
if (payload is int receiptId)
return $"receipt #{receiptId}";
return payload is null ? "dropped: null" : $"unknown: {payload.GetType().Name}";
}
class TextMessage(string body) { public string Body { get; } = body; }
class FormattedTextMessage(string body, string format) : TextMessage(body) { public string Format { get; } = format; }
sealed class ImageMessage(string fileName) { public string FileName { get; } = fileName; }go deeper
Recall that is with a declaration pattern tests and converts in one step, that null never matches, and that the new variable is usable inside the if block whose condition matched.
Explain which conversions count (identity, reference, boxing, unboxing, a Nullable with a value) and which do not (numeric widening, user-defined operators), and show why a boxed long fails an int test.
Use the compiler's checks: CS8121 marks a test that can never succeed and CS0165 marks a pattern variable read where its test may have failed. Order derived-type tests before base-type tests in dispatch code.
Set a convention for type dispatch over object payloads: declaration patterns with an explicit branch for null and for unknown types, so a new payload type shows up as unknown rather than being silently misrouted.
## What a declaration pattern does A chat service's dispatcher receives every payload typed as `object`: a `TextMessage`, an `ImageMessage`, a boxed `int` receipt id, or `null`. To route one, the code has to ask "what is this object really?" and then use it as that type. C# does both in one expression: ```csharp if (payload is TextMessage text) return $"text: {text.Body}"; ``` `TextMessage text` is a **declaration pattern**: a type followed by a **designation**, the name of a new local variable. The `is` operator evaluates `payload` once, tests the value against the pattern and returns `bool`. When the test succeeds, the value is converted to `TextMessage` and stored in `text`, so the `if` body can call `text.Body` with no cast. The test looks at the **run-time type** of the object, not at the declared type of the variable. `payload` is declared as `object`, but what matters is the object it currently refers to. ## Which values match The C# reference lists the conditions. A declaration pattern with type `T` matches when the value is **non-null** and one of these holds: - the run-time type is exactly `T` (an identity conversion); - the run-time type derives from `T`, implements interface `T`, or has another **implicit reference conversion** to `T`; - the value is a `Nullable<T>` whose `HasValue` is `true`, and `T` is its underlying type; - a **boxing or unboxing conversion** exists from the run-time type to `T`, as with a boxed `int` tested against `int`. | Payload at run time | `is TextMessage text` | `is int receiptId` | |---|---|---| | `new TextMessage("hi")` | true, `text` is that object | false | | `new FormattedTextMessage(...)` (derived) | true, same object, typed `TextMessage` | false | | boxed `int` 4711 | false | true, `receiptId` is 4711 | | boxed `long` 4711 | false | false | | `null` | false | false | For a reference type the variable refers to **the same object**: a derived `FormattedTextMessage` matches, and `text.GetType()` still reports `FormattedTextMessage`. For a value type, unboxing copies the value out of the box into the new local. ## What the pattern ignores A declaration pattern is a type test with a capture, not a request to convert. So: - **`null` never matches**, because a null reference has no run-time type to test. - **Numeric conversions are not applied**: a boxed `long` does not match `int`, even though `long` and `int` convert to each other with a cast. - **User-defined conversion operators never run**: a class with an `implicit operator TextMessage(string)` does not make a string match `TextMessage`. ## Where the variable can be used The variable is **definitely assigned when true**: the compiler lets you read `text` only on code paths where the `is` expression returned `true`. Inside the `if` body that is guaranteed. Reading it on a path where the test may have failed, such as an `else` branch, is error CS0165, "Use of unassigned local variable 'text'". The exact reach of the name and the `&&`/`||` rules are worth learning separately; for everyday dispatch, use the variable inside the branch whose condition declared it. ## What the compiler checks before run time Some tests can never succeed, and the compiler says so: 1. With `ImageMessage img` declared as a sealed class unrelated to `TextMessage`, `img is TextMessage t` is error CS8121: "An expression of type 'ImageMessage' cannot be handled by a pattern of type 'TextMessage'." 2. The pattern-less form `img is TextMessage` compiles but warns CS0184: "The given expression is never of the provided ('TextMessage') type". 3. A nullable type in a declaration pattern, as in `count is int? n`, is error CS8116: "It is not legal to use nullable type 'int?' in a pattern; use the underlying type 'int' instead." Write `count is int n`; it matches when the `int?` has a value. ## Reading the dispatcher The example below routes six payloads in order: 1. The `TextMessage` matches the first test. 2. The `FormattedTextMessage` also matches it, because a derived class has an implicit reference conversion to its base. 3. The `ImageMessage` fails the first test and matches the second. 4. The boxed `int` unboxes into `receiptId`. 5. The boxed `long` matches nothing, so it is reported as unknown. 6. `null` fails every type test and is caught by the final `is null` check. Order matters: put the more specific type first when a derived type needs its own branch, because the base-type test above it would already match.
- In C#, how does `payload is int receiptId` treat a boxed int, and what is receiptId?It matches when `payload` holds a boxed `int` and unboxes it, so `receiptId` is a copy of the value, not a reference to the box. A boxed `long`, `short` or `uint` does not match, because the pattern unboxes only to the boxed type itself; test `is long` for those, or convert explicitly.
- When does the C# compiler reject `img is TextMessage t` outright?When the static type of `img` can never hold a `TextMessage`, for example a sealed, unrelated `ImageMessage`. The SDK reports error CS8121, "An expression of type 'ImageMessage' cannot be handled by a pattern of type 'TextMessage'." The pattern-less `img is TextMessage` only warns, with CS0184.
- How does a C# declaration pattern treat an `int?` input?`count is int n` matches when the `int?` has a value (`HasValue` is true) and binds `n` to that value; an empty `int?` fails. Writing `count is int? n` is error CS8116, "It is not legal to use nullable type 'int?' in a pattern; use the underlying type 'int' instead."
- is with a declaration pattern matches null and leaves the variable null
- Only the exact type matches; a derived class fails the test
- A boxed long matches an int pattern through numeric conversion
- The pattern calls a user-defined implicit conversion operator when one exists
- The pattern variable is assigned after the if whether or not the test matched