A blog about one man's journey through code… and some pictures of the Peak District

The Evolution of the Switch Statement (C#8)

Most languages have a version of the switch statement as far as I’m aware; I must admit, I don’t remember one from Spectrum Basic, but ever since then, I don’t think I’ve come across a language that doesn’t have one. The switch statement in C was interesting. For example, the following was totally valid:

switch (value)
{
case 1:
printf("hello ");
case 2:
printf("world");
}

If you gave it a value of 1 would print “hello world”. When C# came out, they insisted on using breaks at the end of case statements, or having no code (admittedly there were a few bugs in C caused by accidentally leaving break statements out):

Anyway, fast forward around 17 years to C# 7.x, and it basically has the same switch statement; in fact, as far as I’m aware, you could write this switch statement in C# 1.1 and it would compile fine. There’s nothing wrong with it, so I imagine MS were thinking why fix it if it’s not broken.

There are limitations, however; for example, what if I want to return the string, like this:

From C# 8, you can do just that. The switch statement will return its value. The case syntax is disposed of, and there’s no need for a break statement (which, to be fair, can encourage people to write large swathes of code inside the switch statement – if you don’t believe me then have a look in the Asp.Net Core source!).

And that’s not all. Pattern matching has also been brought in; for example, take the following simple class structure: