Fun with C# Switches


Url: http://msdn.microsoft.com/library/default.asp?u...

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 ;)



Shawn
Shawn Wildermuth
Author, Teacher, and Coach



My Courses

pluralsight
Building a Web App with ASP.NET Core, MVC6, EF Core, Bootstrap and Angular (updated for 2.0)
Using Visual Studio Code for ASP.NET Core Projects (new)
Implementing and Securing an API with ASP.NET Core
Building a Web App with ASP.NET Core, MVC6, EF Core and AngularJS
Building a Web App with ASP.NET5, MVC6, EF7, and AngularJS (Retired)
Best Practices in ASP.NET: Entities, Validation, and View Models
Webstorm Fundamentals
Front-End Web Development Quick Start
Lessons from Real World .NET Code Reviews
Node.js for .NET Developers

Application Name WilderBlog Environment Name Production
Application Ver 2.0.0.0 Runtime Framework .NETCoreApp,Version=v2.0
App Path D:\home\site\wwwroot\ Runtime Version .NET Core 4.6.26020.03
Operating System Microsoft Windows 10.0.14393 Runtime Arch X86