Wednesday, April 14, 2010

A pet peeve: Switch vs. If/Else If

One of my pet peeves is seeing an if/else tree where there could be a switch statement. I get even more annoyed when I see it in official sample code from Microsoft.

From the MSDN description of System.Web.UI.WebControls.MailDefinition
if (sourcePriority.SelectedValue == "Normal")
{
md.Priority = MailPriority.Normal;
}
else if (sourcePriority.SelectedValue == "High")
{
md.Priority = MailPriority.High;
}
else if (sourcePriority.SelectedValue == "Low")
{
md.Priority = MailPriority.Low;
}


I admit that my reasoning is largely aesthetic - switch statements just look neater, and I find them easier to read. Switch is generally held to be the more efficient of the two, but I will accept that for a 3-option split the performance gain is likely to be negligible.

Also, in this particular case, you could even use Enum.Parse().