Click here to download the sample source code for this switch statement lab exercise
An alternative conditional statement to the “if” in C# is the “switch” statement which allows the programmer to write a more elegant “if” statement. Its purpose is almost the same as the if, else if, else but can be easier to read and maintain in certain situations. With the switch statement, you first have to define a variable that you will be testing for a certain condition or value.
In the Lab2 project, create a new web form. In the Solution Explorer, right click on the project name “Lab2″ at the top and click “Add New Item”. Make sure to click Web Form as the template, leave the name of the page as Default2.aspx, make sure the language is Visual C#, make sure the Place code in separate file is checked on, and click the Add button to create this new form. Go to the Design view for this new page Default2.aspx. Click here to watch an example video.
Drag a Button onto the form and change the Text property to say “switch statement with integer”. Drag a TextBox onto the form next to the Button. Double click on the Button to add the event handler. In the event handler method, put the following code:
int i = 33; switch (i) { case 10: TextBox1.Text = "i = 10"; break; case 33: TextBox1.Text = "i = 33"; break; default: TextBox1.Text = "i is neither 10 nor 33"; break; }
At the top of the switch statement we let C# know that we are going to test the value of the variable i by using the “switch (i)” block of code. Then the switch statement will execute each case from the top and moving downward until it finds a condition that is true. In my example, the switch will not go into the “case 10″ because the value of the variable i is NOT 10. It will go into the “case 33″ block because the value of i matches with 33. The “default” is the last part of the switch statement and is there to let C# know that if none of the above conditions were true, go ahead and execute whatever is in the default portion. This is similar to the “else” in an “if” statement in C#. To demonstrate how the switch statement could have been written using an “if”, the following lines of code would achieve the same thing as the switch statement:
if (i == 10) TextBox1.Text = "i = 10"; else if (i == 33) TextBox1.Text = "i = 33"; else TextBox1.Text = "i is neither 33 nor 44";
To end the switch exercise, I want you to see an example of how the switch statement can be used with different variable types. In the example below, I am using the switch with a string variable type:
string tedstring = "Hello ted"; switch (tedstring) { case "Hello marvin": TextBox2.Text = "Matched with marvin"; break; case "Hello lucy": TextBox2.Text = "Matched with lucy"; break; default: TextBox2.Text = "Matched with ted"; break; }
Notice that I am using string literals to compare to the value of the variable tedstring. Since in this example, neither of the case conditions match, the switch will fall through to the default portion.