How c# compiler looks at switch case statements

Every developer writes a switch case statement at least once in their life of programming but as he/she understands the switch is no longer maintainable they tend to look for patterns and do refactoring.

In this post, we’ll see what’s actually inside of a switch case statement.

The switch-case statement

Here is the snippet of the code

IL of the switch case statement

the IL for the above code

What’s in the IL?

I’ll walk through this IL, at Line 12 in the IL there’s a string equality checking which checks for the case statement to match once it is matched at Line 18 a brtrue.s IL_0028(a branch to target if the value is non-zero) is issued, this will check the result of the above line (the equality comparison).

Let’s consider our best case to match “a” so the control is now transferred to IL_0028 this is where our write line statement at. So, we’ll print that out.

What the IL looks like?

So, to give a glimpse of that IL in C# it is like this

You might be refactoring the above if statements for a cleaner switch case statement but you’d end up with the above code when the compiler transforms the switch.

Wrapping up

If you ever refactor an if-else chain to a simple switch case statement then it is not so good but will be clean as compiler generates the if-else chain for you instead you ending up in tangled between if-else chain.

One tip for those who refactor these if-else statements to switch is that run code metrics tools to see if there is any improvement on the maintainability index. I’m sure there won’t be if the code metric tool really sees this IL stuff.

But, the switch is also not a good thing to do if you think from the design perspective of the application. That is why people tend to introduce the polymorphism instead of switch design or use dictionary patterns.