Home » ASP.NET Basics » 07 - Writing code and handling events
7

The switch-case statement

Defining function and uses of the switch case statement

The switch-case statement is also used for making decision. However, unlike the if-else statement, we can not test conditions like `greater than' or `less than'. In switch-case, we can test the value of a variable and decide what to do if a particular value is stored in the variable. The syntax for the switch-case is:

 switch(variable to test) { case value1: statements if value1 stored in the variable; break; case value2: statements if value12 stored in the variable; break; . . . default: statements if none of the values match; break; }

To understand this, let us assume that there is an integer variable called `day' and the user is required to enter a weekday number (from 1 to 7) in it. A label control will display the name of the day.

 int day; day = Convert.ToInt32(TextBox1.Text); 
 switch(day) { case 1: Label1.Text = "Monday"; break; case 2: Label1.Text = "Tuesday"; break; case 3: Label1.Text = "Wednesday"; break; . . . case 7: Label1.Text = "Sunday"; break; default: Label1.Text = "Invalid day number"; break; }

In the above code, we are testing the value stored in the variable `day'. If the value is 1, the first case will match and the statement in it will execute. Then the keyword `break' will terminate the switch-case. If the value is 2, the second case will match and so on. If the user enters a value that does not match any case, the statement in the default section will execute.

As we can see, to use the switch-case, we need to have some idea of the values that will be tested. Further, we cannot use comparisons like x>y in the switch-case statement. That is why the if-else statement is the preferred one for decision-making.