skip to content

In C#, why does `payload is TextMessage text || payload is null` leave text unusable in the if body, while `payload is not TextMessage text` followed by return does not?

level: seniorimportance: should knowfreq 40%

answer

  1. two rules: scope and assignment
  2. assigned when true
  3. || lets a failed test through
  4. is not assigns when false
  5. an if condition reaches the enclosing block

basics

~20 s

A pattern variable is definitely assigned only where its test succeeded. With ||, the body also runs when that test failed, so reading text is error CS0165; after an is not test that returns, only matching payloads reach the next line.

solid answer

~50 s

The compiler treats a pattern variable as **definitely assigned when true**: it holds a value only on paths where its `is` test succeeded. In `payload is TextMessage text || payload is null`, the body also runs when the left test failed and the right one passed, so `text` may be unassigned and reading it is error CS0165. With `&&` the opposite holds: `text` is assigned in the right operand and in the body. `payload is not TextMessage text` is assigned when **false**, so after `if (payload is not TextMessage text) return;` every path reaching the next line matched. Scope is a separate rule: a variable declared in an `if` condition belongs to the enclosing block, so it stays visible after the `if` and its name cannot be declared again there (CS0128); one declared in a `while` condition exists only inside that loop (CS0103 after it).

code

csharp · 21 lines
csharp
object[] payloads = [new TextMessage("hello"), new TextMessage(""), 4711, null!];
foreach (object payload in payloads)
    Console.WriteLine(Describe(payload));

static string Describe(object? payload)
{
    // Guard clause: text is definitely assigned once the negated test is false.
    if (payload is not TextMessage text)
        return "not a text message";

    // && carries the assignment into its right operand.
    if (text.Body is var body && body.Length == 0)
        return "blank text";

    return $"text: {text.Body}";
}

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

go deeper

for a junior

Recall that a pattern variable is usable where its test succeeded, and that if (payload is not TextMessage text) return; leaves text usable on the following lines.

for a middle

Explain definite assignment when true and when false, why && keeps the variable assigned in the body and || does not, and why an if condition's variable reaches the enclosing block.

for a senior

Read CS0165, CS0103 and CS0128 on pattern variables as flow or scope problems, and restructure conditions into guard clauses rather than adding dummy assignments.

for a principal

Decide whether guard clauses with is not become the team's default for early exits, balancing flatter methods against pattern variables whose names stay reserved for the rest of the block.

## Two separate rules A **pattern variable** is the local a declaration pattern introduces, such as `text` in `payload is TextMessage text`. Two independent rules decide where it can be read: - **Scope** decides where the *name* exists. Outside its scope the compiler reports CS0103, "The name 'image' does not exist in the current context". - **Definite assignment** decides where the variable *certainly holds a value*. Inside its scope but on a path where it may be unassigned, reading it is CS0165, "Use of unassigned local variable 'text'". Most surprises come from mixing the two: a name can be in scope and still unusable. ## Definite assignment through &&, || and ! The C# 7.0 pattern-matching design says each pattern variable is "definitely assigned when true": assigned on the paths where the `is` expression produced `true`. The logical operators carry that state: | Condition | `text` assigned in the if body? | Assigned after `if (...) return;`? | |---|---|---| | `payload is TextMessage text` | yes | no | | `payload is TextMessage text && text.Body.Length > 0` | yes | no | | `payload is TextMessage text \|\| payload is null` | no, CS0165 | no | | `payload is not TextMessage text` | no, CS0165 | yes | | `!(payload is TextMessage text)` | no, CS0165 | yes | The reasoning for each: 1. With `&&`, the right operand runs only if the left one was true, so `text` is already assigned in `text.Body.Length` and in the body. 2. With `||`, the body runs when *either* side is true. If the left test failed and `payload is null` succeeded, `text` was never assigned. 3. `not` and `!` flip the condition, so the variable is assigned when the whole expression is **false**: in the `else` branch, or after an `if` whose body leaves with `return`, `throw`, `break` or `continue`. ## The guard-clause idiom That last row is the **guard clause**: reject what you cannot handle, then work with the narrowed value at the outer level of the method. ```csharp if (payload is not TextMessage text) return "not a text message"; return $"text: {text.Body}"; ``` Every path that reaches the final line passed through the `false` side of the test, so `text` is definitely assigned and the method stays flat instead of nesting its logic inside the `if`. ## How far the name reaches The design document gives a pattern variable's scope by where the `is` expression sits: - In the condition of an **`if` statement** or in an **expression statement**, the scope is the **enclosing block**. That is why the guard clause works, and also why the same name cannot be declared again later in that block: CS0128, "A local variable or function named 'text' is already defined in this scope". - In the condition of a **`while`, `for` or `foreach`** statement, the scope is **just that statement**, so the name is gone after the loop (CS0103). - An **embedded statement**, such as the single statement controlled by an `if`, is its own scope, so a pattern variable declared inside it does not escape. - In an **expression-bodied lambda or member**, the scope is that body; in a **`catch` clause's `when` filter**, the scope is that `catch` clause. ## Reading the diagnostics The second example below compiles to exactly three errors: 1. **CS0165** at `return text.Body;`: the `||` condition lets a path through where `text` was never assigned. 2. **CS0103** at `image.FileName`: `image` was declared in a `while` condition and does not exist after the loop. 3. **CS0128** at `string? text`: the `if` condition's `text` already occupies the method block. ## Repairing the code - Split an `||` test into separate branches, each with its own declaration: handle `payload is null` first, then test `payload is TextMessage text`. - Prefer a guard clause with `is not` when the rest of the method needs the narrowed value. - Rename rather than reuse: pattern variables in `if` conditions share the block's namespace with ordinary locals. - Keep `&&` when the rest of the condition needs the variable, as in `payload is TextMessage text && text.Body.Length > 0`; the right operand runs only after a match.

  • In C#, why can't a method declare another local named `text` after `if (payload is TextMessage text)`?
    A pattern variable declared in an `if` condition belongs to the block containing the `if`, not to the `if` alone, so a later `string? text` in that block is error CS0128, "A local variable or function named 'text' is already defined in this scope". Rename one of them, or move the test into its own method.
  • In C#, how do you keep a pattern variable usable when the same if must also handle null?
    Split the conditions instead of joining them with `||`: handle `payload is null` in its own branch or guard, then test `payload is TextMessage text`. Each branch reads only variables its own condition assigned, so the compiler can prove every read.

  • A pattern variable from an if condition exists only inside that if block
  • The compiler assigns null to the pattern variable when the test fails
  • || keeps the pattern variable assigned in the body just as && does
  • is not TextMessage text makes text usable inside the if body
  • A pattern variable from a while condition is still visible after the loop