Interview Questions

My switch statement works differently! Why?

C# Interview Questions and Answers


(Continued from previous question...)

139. My switch statement works differently! Why?

C# does not support an explicit fall through for case blocks. 
The following code is not legal and will not compile in C#: switch(x)
{
case 0:
// do something
case 1:
// do something in common with 0
default:
// do something in common with
//0, 1 and everything else
break;
}
To achieve the same effect in C#, the code must be modified 
as shown below (notice how the control flows are explicit): class Test
{
public static void Main()
{
int x = 3;
switch(x)
{
case 0:
// do something
goto case 1;
case 1:
// do something in common with 0
goto default;
default:
// do something in common with 0, 1, and anything else
break;
}
}
}

(Continued on next question...)

Other Interview Questions