Floating curly braces in C#
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?
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.
Any variable inside the "scope" of these curly braces will be out of scope outside of it.
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?
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.
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.
The purpose of this is to illustrate that the int i
is actually in a different scope than the incremented i
below it.
精彩评论