Wednesday, October 29, 2008

Really Strange C# Scope Syntax

Did you know you can define a separate variable scope within a C# method? I'm not sure why you would ever want to use this syntax, but it's there if you want it. Simply open a set of squiggly brackets within your method, and define variables within the brackets. The variables will be out of scope when you leave the brackets. Thus, the following code compiles just fine:


public void Run()

{

    int value = 0;

 

    {

        int innervalue = 2;

        Console.WriteLine(innervalue);

    }

 

    {

        string innervalue = "string";

        Console.WriteLine(innervalue);

    }

 

    Console.WriteLine(value);

}

It's important to note that there's nothing especially different about how the C# compiler compiles this code. The declared variables aren't popped from the stack until the method leaves, and nothing unusual happens to them during the execution of the method. All of these values remain on the stack (or the heap) until the method returns. In fact, in the example above, the compiler actually renames the second "innervalue" local variable as "V_2", and references it that way in the IL. So this is just a feature of the language.

Nevertheless, it's a fun trick to show your friends at all your coding parties.

This just goes to show that scope is as simple as knowing that any variables declared within squiggly brackets in C# are unavailable outside the squiggly brackets.