An array of C#, PHP, and HTML programming articles, tutorials, and resources

Posts Tagged ‘ case ’

Switch Statement in C#

by Victor | July 3, 2008 in C# | 3 Comments

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.

A common function used in coding is to compare two strings, but to ignore whether the characters are upper or lower case. Right off the bat, a simple solution would be to simply convert both strings to either upper or lower case, and then execute the comparison (as shown in the example below). In the example below, the result is return true. However, without the ToUpper() function, the following would return false.

string a = "abcdefg";
string b = "aBcDeFg";
if (a.ToUpper() == b.ToUpper())
{
   return true;
}
else
{
   return false;
}

However, a more efficient method is to use a predefined C# function in the String class called Compare. Simply pass to this function two strings you wish to compare. The third input is a boolean variable stating whether to compare the cases. The function outputs zero if they are the same.

public static int Compare(string strA, string strB, bool ignoreCase)

Below is a sample of the Compare function in action on the first example. This example will return true.

string a = "abcdefg";
string b = "aBcDeFg";
if (String.Compare(a, b, true) == 0)
{
   return true;
}
else
{
   return false;
}

Finally, individually measuring the execution time of each method in repetitious manner indicates that String.Compare is more efficient than sets of strings to converted to upper or lower case before the comparison.