Friday, January 30, 2009

I keep learning new things about C#

Apparently, in the body of a method, you can arbitrarily use braces to create 'pockets' of child-local scope. For example:

static void Main(string[] args) {

    int x = 10;

 

    {

        int y = 1;

        Console.WriteLine(x + y);

    }

 

    {

        int y = 2;

        Console.WriteLine(x + y);

    }

 

    Console.ReadLine();

}


This will, as expected, create the output 11 and 12. The variable 'y' is created twice, but in each case it's created in some sort of anonymous child scope. I was always under the impression that you had to have a reason of some sort in order to create child scope like this. Glad to see I was mistaken - this might come in handy some day...

5 comments:

Anonymous said...

This is an old C trick. C doesn't allow you to have declarations other than at the top of a method.

It is also a useful idiom in C++ to enforce quick destruction of a local variable, either for resource cleanup or to give additional hints to the optimizer.

Anonymous said...

I was wondering what that was. I saw it in code at work and have been perplexed ever since. Thanks for solving that mystery for me.

Erik said...

Andy: Not surprised, really, but why it was carried over into C# (with its non-deterministic finalization) I don't understand.

Justin: Really - someone's using this in production code? Any chance you can find out from the author exactly why they did this?

Bobfox said...

Would you mind to post your VS2008 fonts and color settings?

Thanks.

Erik said...

Bobfox - I can do you one better and point you to the place where I got them: http://winterdom.com/weblog/2007/11/22/VS2008ColorSchemes.aspx