Possible Duplicate:
Do you use curly braces for additional scoping?
Floating curly braces in C#
By accident I spotted the following in C#:
if(condition) return true;
{
// perform this if true
}
When investigating, I realised that you can simply apply curly braces to blocks of code, which made me think it would be akin to ‘scoping’ the code:
{
string foo = "foo";
}
string foo = "new foo!";
…but it doesn’t.
Are there any benefits, features or uses of why you would want to do this?
Actually, it does. The reason that you get a compiler error on the code
is because local variables are in scope throughout the entire block in which the declaration occurs. Therefore, the “second” declaration of
foois in scope in the whole block, including “above” where it is declared, and therefore it conflicts with the “first”foodeclared in the inner scope.You could do this:
Now, the two scopes do not overlap and you do not get the compiler error that you are implicitly referring to in saying “…but it doesn’t.”
It lets you use the same simple name in two different blocks of code. I think this is in general a very bad idea, but that is what this feature lets you do.