Wednesday, July 14, 2010

Switch-Case Statements - C#

A Switch-Case statement is essentially the same thing as an If-Else If-Else statement. In other languages it is called a Select-Case statement. What it does is pick a variable, then check the value of the variable against different cases. If a case matches the value of the variable, the program executes the code within that case statement. There is also the option to add a 'default' case, which is the same thing as the last 'else' in a series of If statements.

Note: Every case statement must end with a 'break;', signifying the end of that case's code.

Here is a simple example using a Switch-Case statement.

With ints:
int test = 3;

switch(test)
{
   case 1:
      Console.WriteLine("1");
      break;
   case 2:
      Console.WriteLine("2");
      break;
   case 3:
      Console.WriteLine("3");
      break;
   default:
      Console.WriteLine("Int is not 1-3");
      break;
}
Output: 2

With Strings:
string test = "Weeee!";

switch(test)
{
   case "Wee.":
      Console.WriteLine("Meh.");
      break;
   case "Weee.":
      Console.WriteLine("Eh.");
      break;
   case "Weeee!":
      Console.WriteLine("Now You're Excited!");
      break;
   default:
      Console.WriteLine("Do Something");
      break;
}
Output: Now You're Excited!

0 comments:

Post a Comment