C# - The switch statement

Posted Jun 09, 2009 by Victorius / comments 0 comments / Print / Font Size Decrease font size Increase font size

Another important statement is the switch statement. Now we will learn it :)

The switch statement is like a set of if statements. It's a list of possibilities, with an action for each possibility, and an optional default action, in case nothing else evaluates to true. A simple switch statement looks like this:

int number = 1;
switch(number)
{
case 0:
Console.WriteLine("The number is zero!");
break;
case 1:
Console.WriteLine("The number is one!");
break;
}

The identifier to check is put after the switch keyword, and then there's the list of case statements, where we check the identifier against a given value. You will notice that we have a break statement at the end of each case. C# simply requires that we leave the block before it ends. In case you were writing a function, you could use a return statement instead of the break statement.

In this case, we use an integer, but it could be a string too, or any other simple type. Also, you can specify the same action for multiple cases. We will do that in the next example too, where we take a piece of input from the user and use it in our switch statement:

Console.WriteLine("Do you enjoy C# ? (yes/no/maybe)");
string input = Console.ReadLine();
switch(input.ToLower())
{
case "yes":
case "maybe":
Console.WriteLine("Great!");
break;
case "no":
Console.WriteLine("Too bad!");
break;
}

In this example, we ask the user a question, and suggest that they enter either yes, no or maybe. We then read the user input, and create a switch statement for it. To help the user, we convert the input to lowercase before we check it against our lowercase strings, so that there is no difference between lowercase and uppercase letters. Still, the user might make a typo or try writing something completely different, and in that case, no output will be generated by this specific switch statement. Enter the default keyword!

Console.WriteLine("Do you enjoy C# ? (yes/no/maybe)");
string input = Console.ReadLine();
switch(input.ToLower())
{
case "yes":
case "maybe":
Console.WriteLine("Great!");
break;
case "no":
Console.WriteLine("Too bad!");
break;
default:
Console.WriteLine("I'm sorry, I don't understand that!");
break;
}

If none of the case statements has evaluated to true, then the default statement, if any, will be executed. It is optional, as we saw in the previous examples.

Rate this Article:

Be the first to rate me.


* You must be logged in order to leave comments, please login or join us.

Comments

No comments yet.


This work is licensed under
Republish Article Report Content  



Bookmark and Share
Sign up for our email newsletter
Name:
Email: