I am certain that many of you encountered a need for a code like this:
switch (controlVariable)
{
case 1:
int i = 10;
Console.Out.WriteLine(i);
break;
case 2:
int i = 20; // compiler error here
Console.Out.WriteLine(i);
break;
}
This is not possible because the whole switch acts as a “declaration space” and only one declaration of the “i” variable is allowed. In order to overcome this, one has somehow to trick the compiler into considering each case as having its own declaration space. How we make this? Use the brackets:
switch (controlVariable)
{
case 1:
{
int i = 10;
Console.Out.WriteLine(i);
break;
}
case 2:
{
int i = 20;
Console.Out.WriteLine(i);
break;
}
}



Entries (RSS)