Besides the if statement, the other conditional statement in C# is the switch statement. This statement acts much like an extended if statement; it can handle multiple tests in a single statement, checking a test expression against various values and executing code when the test expression matches one of the values you've tested it against. Here's what the switch statement looks like formally in C#: switch ( expression ) { case constant-expression : statement jump-statement [default: statement jump-statement ] } Here are the parts of this statement:
Here's how it works: Control is transferred to the case statement whose constant-expression matches expression . If no case statement matches the test expression, the code in the default statement (if present) is executed.
You can see an example, ch01_11.cs, in Listing 1.11. This program asks the user to guess a number (5), and it checks the user 's guess against the mystery number with a switch statement. Listing 1.11 Using the switch Statement (ch01_11.cs)using System; class ch01_11 { static void Main() { Console.Write("Guess my number (1-5): "); int input = Convert.ToInt32(Console.ReadLine()); switch (input) { case 1: Console.WriteLine("Wrong, sorry.\n"); break; case 2: case 3: Console.WriteLine("Neither 2 nor 3 is correct.\n"); break; case 4: goto case 1; case 5: Console.WriteLine("Right!\n"); break; default: Console.WriteLine("Not a valid guess!\n"); break; } } } If the user guesses 1, the first case in the switch statement will be executednote the break statement at the end, which terminates the switch statement: case 1: Console.WriteLine("Wrong, sorry.\n"); break; If the user guesses 2, control will fall through to case 3 , because there is no code for case 2 (note that if you place any code in case 2 , but omit a break or goto statement, you'll get a compilation error): case 2: case 3: Console.WriteLine("Neither 2 nor 3 is correct.\n"); break; If the user guesses 4, we send them to the code for case 1 with a goto statement, which transfers control to the code in the case we specify: case 4: goto case 1; And if the user guesses 5, they're right, and we admit the fact: case 5: Console.WriteLine("Right!\n"); break; We've taken care of the numbers 15, and if we still haven't left the switch statement, the user must have entered an invalid guess. We can handle that error with the (optional) default statement, which (if present) is executed if no case statement matches: default: Console.WriteLine("Not a valid guess!\n"); break; |