14

I ran across a piece of C# code today I had not seen before. The programmer defined a block of code using only curly braces (no if, class, function, etc).

{
    int i = 0;
}
i++; //compile error

Is there a purpose to this other than making the code look more organized? Is it good, bad, or whatever practice to use this "floating" contexts?

Rob
  • 26,989
  • 16
  • 82
  • 98
prestomanifesto
  • 12,528
  • 5
  • 34
  • 50
  • http://stackoverflow.com/questions/249009/do-you-use-curly-braces-for-additional-scoping – luketorjussen Aug 30 '11 at 16:48
  • 1
    sorry about the duplicate question, I thought I had googled pretty hard! – prestomanifesto Aug 30 '11 at 17:25
  • 1
    This should not have been marked **duplicate** to a 2008 question that was edited in 2010 to **incorrectly** include `c#` when all the answers are **clearly not c#**. Nominating that it be **re-opened** –  Aug 24 '16 at 23:56

6 Answers6

15

You can use an open and close set of curly braces to define a self containing block, which has its own scope.

This is generally not considered good programming practice, though.

Usually if someone is doing something like this, it's probably better to create a method/function in its place.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Joseph
  • 25,330
  • 8
  • 76
  • 125
2

Any variable inside the "scope" of these curly braces will be out of scope outside of it.

RBZ
  • 2,034
  • 17
  • 34
1

There is no purpose to that code at all. Probably an artifact from something else he/she was trying to do. As the comment shows this won't even compile because i is out of scope.

From a coding style perspective I personally don't like it and I've never seen someone use floating braces to "organize" their code before.

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
1

The braces {} in C# define scope. Anything defined within them goes "out of scope" once the braces are terminated.

The example seems kind of pointless. I can't imagine why it would be used in real world code. I'm assuming you pared down the code presented?

Yuck
  • 49,664
  • 13
  • 105
  • 135
  • 1
    Ya. The way it was actually used was in an ASP page that was manually rendering some html code. The braces were used to indent logically what was inside each element. – prestomanifesto Aug 30 '11 at 17:23
1

It limits the scope of the variable to within that block. So the variable i would not be able to be seen outside of those braces.

It can also be a preference on if someone wants to separate code but using this when not necessary would in most cases be superfluous.

bigphildogg86
  • 176
  • 1
  • 7
  • 17
0

The purpose of this is to illustrate that the int i is actually in a different scope than the incremented i below it.

davecoulter
  • 1,806
  • 13
  • 15