3

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?

Community
  • 1
  • 1
Phil Cooper
  • 3,083
  • 39
  • 63
  • Apologies, missed this - just spotted this has been answered http://stackoverflow.com/questions/7246755/floating-curly-braces-in-c-sharp – Phil Cooper Apr 02 '12 at 16:00

4 Answers4

10

...but it doesn't.

Actually, it does. The reason that you get a compiler error on the code

{
    string foo = "foo";
}

string foo = "new foo!";

is because local variables are in scope throughout the entire block in which the declaration occurs. Therefore, the "second" declaration of foo is in scope in the whole block, including "above" where it is declared, and therefore it conflicts with the "first" foo declared in the inner scope.

You could do this:

{
    string foo = "foo";
}

{
    string foo = "new foo!";
}

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."

Are there any benefits, features or uses of why you would want to do this?

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.

jason
  • 236,483
  • 35
  • 423
  • 525
1

It does add an additional scope to the code, such that the following is legal.

{
    string foo = "foo";
}

{
    string foo = "foo2";
}
davisoa
  • 5,407
  • 1
  • 28
  • 34
0

Yes, it does scope that code. You can do this:

{
  string foo = "foo";
}

if (someCondition)
{
  string foo = "new foo!";
}
Dr. Wily's Apprentice
  • 10,212
  • 1
  • 25
  • 27
0

It is scoping the code. The problem with your experiment is that the outer scope conflicts with the inner scope. Consider:

public void ScopedFoo {
    {
      string foo = "foo";
    }
    {
      string foo = "bar";
    }
}
Chris Shain
  • 50,833
  • 6
  • 93
  • 125