Switch upon string values in CSharp

Description

The following code shows how to switch upon string values.

Example


/*from   w w  w.j a  v a  2  s  . c om*/
public class MainClass
{

  public static void Main()
  {

    string planetName = "Saturn";  // sixth planet from the Sun
    switch (planetName)
    {
      case "Mercury":
        System.Console.WriteLine(1);
        break;
      case "Venus":
        System.Console.WriteLine(2);
        break;
      case "Earth":
        System.Console.WriteLine(3);
        break;
      case "Mars":
        System.Console.WriteLine(4);
        break;
      case "Jupiter":
        System.Console.WriteLine(5);
        break;
      case "Saturn":
        System.Console.WriteLine(6);
        break;
      case "Uranus":
        System.Console.WriteLine(7);
        break;
      case "Neptune":
        System.Console.WriteLine(8);
        break;
      case "Pluto":
        System.Console.WriteLine(9);
        break;
      default:
        System.Console.WriteLine("Planet unknown");
        break;
    }

  }

}

The code above generates the following result.





















Home »
  C# Tutorial »
    C# Language »




C# Hello World
C# Operators
C# Statements
C# Exception