A pair of braces (not brackets -- []
-- and not parentheses -- ()
-- but braces {}
) with zero or more statements in them is a legal statement in C#, and therefore may appear anywhere that a statement may legally appear.
As others have pointed out, the typical reason for doing so is because such a statement introduces a new local variable declaration space, which then defines the scope of the local variables declared within it. (Recall that the "scope" of an element is the region of program text in which the element may be referred to by its unqualified name.)
I note that this is particularly interesting in a switch
statement because the scoping rules in a switch are a little bit strange. For details of how strange they are, see "Case 3:" in my article on the subject:
http://ericlippert.com/2009/08/13/four-switch-oddities/
Braces {} are used to define a scope for a set of operations. Bizarrely, the following will compile and work:
private void ConnectionStateChange(object sender, StateChangeEventArgs e)
{
string s = "hi";
switch(s)
{
case "hi":
{
int a = 1;
a++;
}
{
int a = 2;
a++;
}
break;
}
{
int a = 1;
a++;
}
{
int a = 2;
a++;
}
}
As you can see, in that one method I've created four variables, each called a. Each is entirely separate because, as local variables, they exist only within their own scope.
Does that make some sort of sense?
It creates a new scope in which you can create new variables.
It creates new scope for variables you used. Scope of variables can be tricky sometimes. For instance in the code you posted;
switch(x)
{
case(a):
{
int i = 0;
}
break;
case(b):
i = 1; // Error: The name 'i' doesn't exist in the current context
break;
}
The error makes sense here as in case(b)
variable a
is accessed out of scope. Now on the other hand,
switch(x)
{
case(a):
{
int i = 0;
}
break;
case(b):
int i = 1; // Error: A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'child' scope to denote something else
break;
}
Above two errors look contradictory to each other. To get around this you should define the scope separately in both case statements,
switch(x)
{
case(a):
{
int i = 0;
}
break;
case(b):
{
int i = 1; // No error
}
break;
}
Eric Lippert shared a very good link to his blog to explain variable scopes in case statement. You should have a look at it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With