How to use strings in switch statement in C#

CsharpServer Side ProgrammingProgramming

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
raja
Published on 11-Dec-2019 11:44:47
Advertisements