What is the benefit/downside to using a switch
statement vs. an if/else
in C#. I can\'t imagine there being that big of a difference, other than m
Interest question. This came up a few weeks ago at work and we found an answer by writing an example snippet and viewing it in .NET Reflector (reflector is awesome!! i love it).
This is what we discovered: A valid switch statement for anything other than a string gets compiled to IL as a switch statement. However IF it is a string it is rewritten as a if/else if/else in IL. So in our case we wanted to know how switch statements compare strings e.g is case-sensitive etc. and reflector quickly gave us an answer. This was useful to know.
If you want to do case-sensitive compare on strings then you could use a switch statement as it is faster than performing a String.Compare in an if/else. (Edit: Read What is quicker, switch on string or elseif on type? for some actual performance tests) However if you wanted to do a case-insensitive then it is better using a if/else as the resulting code is not pretty.
switch (myString.ToLower())
{
// not a good solution
}
The best rule of thumb is to use switch statements if it makes sense (seriously), e.g:
If you need to manipulate the value to feed into the switch statement (create a temporary variable to switch against) then you probably should be using an if/else control statement.
An update:
It is actually better to convert the string to uppercase (e.g. ToUpper()
) as that has been apparently there are further optimizations that the just-in-time compiler can do as when compared to the ToLower()
. It is a micro optimization, however in a tight loop it could be useful.
A little side note:
To improve the readability of switch statements try the following: