What is the purpose of the extra braces in Switch case?
c#, switch-statement
Solution
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?
Problem
I'm curious about this thing... see example: ``` switch(x) { case(a): { //do stuff } break; case(b): //do stuff break; } ``` All my life I've done it like case b, but since C# allows me to use it, and Visual Studio allows me to collapse that thing, I am curious - what is the real difference between case a (with braces) and case b?