Skip to main content
CSharpUniversity ASP.NET and C# lessons

The search runs entirely in your browser over the published lesson list.

Where a variable can be seen

A variable exists only inside the block of braces where it was declared. That rule explains most name errors.

Inside and outside

C#
private void Show()
{
    int outer = 5;

    if (outer > 0)
    {
        int inner = 10;
        outputLabel.Text = (outer + inner).ToString();
    }

    // inner is not visible here
}

The rules in plain words

  • A variable declared inside a block is visible only in that block and the blocks nested within it.
  • A variable declared in the class but outside a method is visible to every method in the class.
  • An inner block may reuse an outer name, which hides the outer value and confuses readers, so avoid it.
Declare late and close. Declare a variable just before you use it, in the smallest block that works. It makes the code easier to read and the lifetime easier to reason about.

Scope often matters because of how objects are stored, which leads to value types compared with reference types.

New lessons by email

Leave your address and get a short note whenever a fresh lesson is published. No account needed and you can stop at any time.

Thank you. Your address has been noted in this browser session. Connect a mailing service to deliver the notes for real.