:: KBs ::

C# Switch

Created Date: 4/23/2008
Last Modified Date: 4/23/2008
If you are developing code that contains a lot of conditional statements one of the best techniques to use is a switch statement. A switch statement allows a developer to write cases that are possible values for a particular syntax. Unlike the ‘if statement’, a switch cannot have multiple parts to it. By this there cannot be two or more conditions to meet. Also, all of the conditions have to be part of the same element.

The general syntax is:

switch (value)
{
   case value1:
      statements;
      break;
   …
   case value[n]:
      statements:
      break;
   default:
      statements:
      break;
}

If an ‘if statement’ was this:

if (value == “A”)
{
return “itemA”;
}
else if (value == “B”)
{
   return “itemB”;
}
else
{
   return “itemC”;
}

Then the switch code would be the following:

switch (value)
{
   case “A”:
      return “itemA”;
   case “B”:
      return “itemB”;
   default:
      return “itemC”;   
}

Why would the switch be better than the ‘if statement’? The primary answer is the switch only needs to make one call to the ‘value’. This will reduce cycles for unnecessary calls to grab the same data.
:: Better Coding Practices ::