How to use strings in switch statement in C#


A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

Example

Here is an example to use strings in a switch statement −

 Live Demo

using System;
public class Demo {
   public static void Main(String[] args){
      string grades = "A1";
      switch (grades) {
         case "A1":
            Console.WriteLine("Very good!");
            break;
         case "A2":
            Console.WriteLine("Good!");
            break;
         case "B1":
            Console.WriteLine("Satisfactory!");
            break;
            default:
         Console.WriteLine("Invalid!");
            break;
      }
      Console.WriteLine("Grade = "+grades);
   }
}

Output

This will produce the following output −

Very good!
Grade = A1

Updated on: 11-Dec-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements