When possible, a programmer should choose to use a switch statement over an if statement. Note that it is not always possible to replace an if statement with a switch statement. The right time to use a switch statement is when the if statement is constantly comparing the same variable. In our example, we are constantly comparing the text in the Label control lblDayOfWeek. To make it easy, I have made blue the string text that will be used in our comparison.
switch (lblDayOfWeek.Text)
{
case “1″:
lblDayOfWeek.Text = “Sunday”;
break;
case “2″:
lblDayOfWeek.Text = “Monday”;
break;
case “3″:
lblDayOfWeek.Text = “Tuesday”;
break;
case “4″:
lblDayOfWeek.Text = “Wednesday”;
break;
case “5″:
lblDayOfWeek.Text = “Thursday”;
break;
case “6″:
lblDayOfWeek.Text = “Friday”;
break;
case “7″:
lblDayOfWeek.Text = “Saturday”;
break;
default:
lblDayOfWeek.Text = “”;
break;
}
The final default is equivalent to else, which means if none of the cases match, the default route will be taken. The greatest advantage to using the switch statement is efficiency. When a swtich statement is called, only one comparison is made.
Note that the switch statement is not restricted to string or integer. It is also possible to use enum or virtually any other comparable variable.
This entry was posted on Thursday, July 3rd, 2008 at 7:29 am and is filed under C#. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.


It is definitely more efficient than a if/if-else statement, but it is not always one comparison, i.e. O(1). The compiler will optimize the code, but with large sets it’s sometimes O(n) operations.
http://forums.msdn.microsoft.com/en/csharpgeneral/thread/416b4f5d-792d-4128-9491-70defa7a97d8/
July 7th, 2008 at 9:12 am
Trevor - Thanks for the link. I didn’t realize it and will keep that in mind the next time I have a large set.
July 8th, 2008 at 9:16 am
bading
July 28th, 2008 at 9:19 pm