Blog Stats
  • Posts - 157
  • Articles - 0
  • Comments - 67
  • Trackbacks - 19

 

Wednesday, November 22, 2006

When to use a switch statement/if statement?

Today someone asked me if I had told developer X that having a lot of if statements was better than a having a switch statement. I guess that developer X misunderstood what I told him a couple of weeks ago.

I told him that if you have only 2 conditions that you need to check you can consider using an if statement. If you have more than 2 conditions use a switch statement instead and if you have more than 5 conditions then you should reconsider your design and make use of the command pattern or make better use of inheritance.

When you use a switch statement the C# compiler performs several optimizations. It can rearrange the conditions when needed depending on the frequency and it will also determine whether to implement a jump table (the switch IL instruction) over a if statement instead. Therefore in almost 100% of the cases it is always better to use a switch statement where possible.


Cross-posted from The .NET Aficionado
 

 

Copyright © Gabriel Lozano-Morán