Search code examples
c#variablesscope

Why does C# allow variable scope to extend throughout a block regardless of declaration order?


I am reading a book titled C#10 in a Nutshell by Joseph Albahari OReilly. When describing local variables, the book says the following:

int x; 

{ 
    int y; 
    int x; // Error - x already defined 
} 

{ 
    int y; // OK - y not in scope 
} 

Console.Write (y); // Error - y is out of scope 

A variable’s scope extends in both directions throughout its code block. This means that if we moved the initial declaration of x in this example to the bottom of the method, we’d get the same error. This is in contrast to C++ and is somewhat peculiar, given that it’s not legal to refer to a variable or constant before it’s declared.

  • Chapter 2 of C#10 in a Nutshell

Could someone please explain what this means?


Solution

  • A { } pair encloses a new "scope", a block where a certain variable is valid.

    Both y's are declared in sibling scopes. They will not interfere with each other. Also they will not be available in a parent scope - that's why the Console.WriteLine fails.

    However, one x is defined in the "parent" scope and another in a child scope. This child declaration clashes with the one declared in the parent scope. And this would even be the case when you move the "parent" int x to the end of the block, even though it is then not valid to use it earlier.

    {
        int x; // Error - x already defined 
    }
    
    int x;
    

    Copying in comments:

    Q: So why doesn't it allow us to declare a new int x inside the brackets?

    My A: If you have different x's at both child and parent level, you cannot use the parent-x from within the child level. My guess is that to prevent that issue, the compiler just forbids shadowing a higher-level declaration.