skip to content

In C#, why does reading a local assigned only inside an if fail with CS0165, while an unassigned field reads as zero?

level: juniorimportance: should knowfreq 45%

answer

  1. the compiler proves it, path by path
  2. fields and arrays start zeroed
  3. a loop may run zero times
  4. scope is the whole block
  5. no reusing an enclosing name

basics

~20 s

C# requires every local to be definitely assigned on every path before it is read, and CS0165 reports any path that skips the assignment. Fields and array elements start zeroed when their memory is created, so they need no such proof.

solid answer

~40 s

Definite assignment is a compile-time flow analysis: before a local is read, the compiler must see an assignment on every path that reaches the read. It follows paths, not run-time values, so `decimal rate; if (rows.Length > 1) rate = 0.2m; Console.WriteLine(rate);` is error CS0165 even if every real input has two rows. Loops count as possibly running zero times, and `total += amount` reads `total` first. Fields and array elements are different: their memory is zeroed when the object or array is created, so reading them is defined. Fix it by initializing at the declaration or assigning on every branch. Scope follows a related rule: a local's scope is its whole block, so a nested block cannot declare the same name (CS0136), and reading it above its declaration is CS0841.

code

csharp · 14 lines
csharp
using System;

Console.WriteLine(SumAmounts(["1200", "n/a", "950"]));

static decimal SumAmounts(string[] rows)
{
    decimal total = 0m;
    foreach (var row in rows)
    {
        if (decimal.TryParse(row, out var amount))
            total += amount;
    }
    return total;
}

go deeper

for a junior

Remember the rule: a local must be assigned on every path before it is read, fields and array elements start at zero, and CS0165 is a compile error.

for a middle

Explain how the flow analysis treats if without else, loops that may not run, compound assignment and out arguments, and why a local's scope covers its whole block.

for a senior

Read a CS0165 or CS0136 in review as a design signal: an accumulator without a starting value, a branch that forgot a case, or two variables that should have been one.

for a principal

The tradeoff angle is small: definite assignment costs a few explicit initializers and removes a class of uninitialized-value bugs, so teams accept it rather than work around it.

## Definite assignment is a compile-time proof C# requires every local variable to be **definitely assigned** before its value is read. "Definitely assigned" is a property the compiler proves with **flow analysis** over the method's control flow: on every path that reaches a read, some statement must have assigned the variable. If any path skips the assignment, the compiler reports **CS0165** ("Use of unassigned local variable 'rate'") and the build fails. It is an error, not a warning, so `#pragma warning disable` cannot silence it. The analysis follows paths, not run-time values. It does not know that `rows` always has two entries in production, so this fails: ```csharp decimal rate; if (rows.Length > 1) rate = 0.2m; Console.WriteLine(rate); // CS0165: the false path never assigns rate ``` ## Locals versus fields and array elements Fields and array elements have no such rule. The difference is about who guarantees the starting value: | Storage | Starting value | Reading before any assignment | |---|---|---| | Local variable | none the language promises | compile error CS0165 | | Instance or static field | zero, `false` or `null` | allowed; CS0649 may warn about a private field that is never assigned | | Array element | zero, `false` or `null` | allowed | | `out` argument after the call | whatever the callee assigned | allowed | Fields and array elements live in memory that is zeroed when the object or array is created, so reading them is always defined. A local only has a meaningful value once code assigns it, so the compiler insists on the proof. In practice the rule catches real bugs: a payroll total that started from an unintended value would be far worse than a build error. ## How the analysis treats common shapes - **`if` without `else`**: the variable is unassigned on the false path. - **`if` and `else` that both assign**, or one assigns and the other throws or returns: definitely assigned afterwards. - **Loops**: the body may run zero times, so an assignment that happens only inside a `foreach` does not count after the loop. - **Compound assignment** such as `total += amount` reads `total` first, so `decimal total;` followed by `total += amount;` is CS0165 on that line. - **`out` arguments**: `decimal.TryParse(row, out var amount)` definitely assigns `amount` once the call returns. Constant conditions are the one place the compiler looks at values: in `if (true) x = 1;` the false branch is unreachable, so `x` counts as assigned. A condition computed at run time is treated as possibly true and possibly false. ## Scope: one name per block chain The **scope** of a local is the whole block it is declared in, including the text before its declaration. That rule produces three errors reviewers meet: - **CS0136**: a nested block declares a name that an enclosing block also declares, whether the outer declaration comes before or after the nested block. `{ int row = 1; } int row = 2;` fails, because the outer `row`'s scope covers the inner block. The message reads "A local or parameter named 'row' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter". - **CS0841**: using a local earlier in its block than its declaration ("Cannot use local variable 'x' before it is declared"). - **CS0844**: the same mistake when the name would otherwise mean a field: "Cannot use local variable 'total' before it is declared. The declaration of the local variable hides the field 'Importer.total'." What is allowed: - **Sibling blocks** may reuse a name: two separate `{ int tmp = 1; }` blocks, or two `for (int i = 0; ...)` loops, compile. - A **local may hide a field** of the same name without any warning; `this.total` still reaches the field. - Since **C# 8**, a lambda or local function may declare a parameter or local that shadows an enclosing local, so `Func<int, int> next = row => row + 1;` compiles even with a `row` local outside it. ## Fixing the payroll import 1. Initialize accumulators at the declaration: `decimal total = 0m;`. 2. When branches choose a value, assign it on every branch, or use a conditional expression so declaration and assignment are one statement. 3. Rename instead of re-declaring a name in a nested block; CS0136 usually points at two variables that should have been one, or at one that needs a clearer name.

  • Why is `{ int row = 1; }` followed later by `int row = 2;` in the enclosing block an error, even though the inner block has ended?
    A local's scope is the entire block that declares it, not just the lines after the declaration. The outer `row` is therefore in scope across the earlier nested block too, and the compiler reports CS0136 for the inner declaration. Using the outer `row` above its declaration would be CS0841. Two sibling blocks, by contrast, may each declare their own `row`.
  • Can a lambda inside a method declare a parameter with the same name as a local of that method?
    Yes, since C# 8. Lambda and local function parameters and locals may shadow names from the enclosing method, so `Func<int, int> next = row => row + 1;` compiles beside a `row` local, and inside the lambda `row` means the parameter. Before C# 8 the same code was a scope error. Shadowing a local from a nested ordinary block is still CS0136.

  • Unassigned locals default to zero, just like fields
  • CS0165 is a warning that a pragma can suppress
  • The compiler knows rows is never empty, so the loop counts as assigning total
  • An inner block may redeclare a local from the enclosing block
  • A local declared after a nested block is not in scope inside that block
  • Fields need the same definite-assignment proof as locals