Reputation: 12796
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?
Upvotes: 16
Views: 10305
Reputation: 25523
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.
Upvotes: 16
Reputation: 85056
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.
Upvotes: 0
Reputation: 176
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.
Upvotes: 1
Reputation: 2074
Any variable inside the "scope" of these curly braces will be out of scope outside of it.
Upvotes: 3
Reputation: 50855
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?
Upvotes: 1
Reputation: 1826
The purpose of this is to illustrate that the int i
is actually in a different scope than the incremented i
below it.
Upvotes: 1