Geeks With Blogs
Gabriel Lozano-Morán blog

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 Posted on Wednesday, November 22, 2006 4:46 PM C# | Back to top


Comments on this post: When to use a switch statement/if statement?

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Gabriel Lozano-Morán | Powered by: GeeksWithBlogs.net