Tuesday, November 20, 2012

My switch statement works differently than in C++! Why?

Tags

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 as continuation of case 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;
  }
 }
}


EmoticonEmoticon