11.4. Conditional statements with the switch andcase keywords

C# has made one efficient change for the switch clause to accept strings in addition to integral expressions. The switch statement in Java can only accept the byte, short, char, and int primitive types.

Examine the following program which uses switch to compare a string (ignore the goto statement for now, it will be explained later).

 1:  using System;
 2:
 3:  class TestClass{
 4:    public static void Main(string []args){
 5:      string s = args[0];
 6:
 7:      switch(s){
 8:            case "jam" : Console.WriteLine("BUTTER");
 9:                         goto case "butter";
10:
11:            case "cake": Console.WriteLine("CAKE");
12:                         break;
13:
14:            case "bug" : Console.WriteLine("BUG");
15:                         break; 16: 17: case "fly" : Console.WriteLine("FLY"); ...

Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.