Fun with C# Switches

February 6, 2006
No Comments.


Interesting what can happen when you re-read the specification.  I’ve been taking time in the “library” to read the 2.0 C# Specification. But instead of skiping the old stuff and concentrating on the new language stuff, I am reading the whole thing again. Something interesting I found in the ‘switch’ statement.

I am an old C++ hack from the COM days so I assumed that I knew how the switch worked:

int x = 1;
switch (x){  case 1:      Console.WriteLine("1");      break;  case 2:    Console.WriteLine("2");    break;  default:    Console.WriteLine("Unknown");    break;}

Pretty basic stuff.  But because of my C++ legacy, I assume that this wouldn’t work (which it does):

switch (x){  default:    Console.WriteLine("Unknown");    break;  case 2:    Console.WriteLine("2");    break;  case 1:    Console.WriteLine("1");    break;}

Ok, so order isn’t that important (though I like the style of the default first). But because we don’t have fall-through like in C++, I thought that linking multiple cases was kinda hacky…of course its because I didn’t know about goto case:

switch (x){  case 1:    goto default;  case 2:    Console.WriteLine("2");    break;  case 3:    goto case 2;  default:    Console.WriteLine("Unknown");    break;}

Look closely at two lines if you’re not familiar with it.  The ‘goto default’ indicates to go to the default case; while the 'goto case 2’ says go to the code inside case 2!  To further illustrate, this is what it would look like with a string switch:

string s = "3";switch (s){  case "1":    goto default;  case "2":    Console.WriteLine("2");    break;  case "3":    goto case "2";  default:    Console.WriteLine("Unknown");    break;}

Notice the ‘goto case “2”’ mimics the actual case label, so depending on what you’re switching on, you’d change that for your case statement.  Pretty sweet.

Just don’t tell Microsoft I just learned this otherwise they might take my C# MVP away ;)