![]() ![]() ![]() | introductory-examples/control-structures/control-demo.cs - A Demonstration of switch. | Lecture 0 - slide 8 : 25 Program 2 |
public static void SwitchDemo(){ int j = 1; /* Illegal: Control cannot fall through from one case label to another switch (j) { case 0: Console.WriteLine("j is 0"); case 1: Console.WriteLine("j is 1"); case 2: Console.WriteLine("j is 2"); default: Console.WriteLine("j is not 0, 1 or 2"); } */ /* Break or similar jumping is needed: */ switch (j) { case 0: Console.WriteLine("j is 0"); break; case 1: Console.WriteLine("j is 1"); break; case 2: Console.WriteLine("j is 2"); break; default: Console.WriteLine("j is not 0, 1 or 2"); break; } /* Falling through empty cases is possible: */ switch (j) { case 0: case 1: Console.WriteLine("j is 0 or 1"); break; case 2: case 3: Console.WriteLine("j is 2 or 3"); break; case 4: case 5: Console.WriteLine("j is 4 or 5"); break; default: Console.WriteLine("j is not 1, 2, 3, 4, or 5"); break; } /* It is possible to switch on strings: */ string str = "two"; switch (str) { case "zero": Console.WriteLine("str is 0"); break; case "one": Console.WriteLine("str is 1"); break; case "two": Console.WriteLine("str is 2"); break; default: Console.WriteLine("str is not 0, 1 or 2"); break; } }