Use Strings in Switch Statement in C#

This article will introduce a method to use the string in the switch statement in C#.

Use Strings in the switch Statement in C#

There is no special method of using strings in the switch statement. We can simply create cases by assigning the value in double-quotes that represents a string.

The program below shows how we can use strings in the switch statement in C#.

using System; 
  
class StringinSwitch { 
    static public void Main() 
    { 
        string mystring = "Rose"; 

        switch (mystring) { 
            case "Jasmine": 
                Console.WriteLine("The flower is Jasmine"); 
                break; 
      
            case "Lili": 
                Console.WriteLine("The flower is Lili"); 
                break; 
            case "Rose": 
                Console.WriteLine("The flower is Rose"); 
                break; 
            case "Hibiscus": 
                Console.WriteLine("The flower is Hibiscus"); 
                break;
            case "Daisy": 
                Console.WriteLine("The flower is Daisy"); 
                break; 
      
            default: 
                Console.WriteLine("No Flower Selected"); 
                break; 
        } 
    }
} 

Output:

The flower is Rose

We have passed the string in the switch statement. The switch statement has returned the value according to the value to the given string.

If we pass a string that is not in the cases, then the switch statement will use the default case.

using System; 
  
class StringinSwitch { 
        static public void Main() 
    { 
        string mystring = "Sun Flower"; 
          
        switch (mystring) { 
              
        case "Jasmine": 
            Console.WriteLine("The flower is Jasmine"); 
            break; 
  
        case "Lili": 
            Console.WriteLine("The flower is Lili"); 
            break; 
        case "Rose": 
            Console.WriteLine("The flower is Rose"); 
            break; 
        case "Hibiscus": 
            Console.WriteLine("The flower is Hibiscus"); 
            break;
        case "Daisy": 
            Console.WriteLine("The flower is Daisy"); 
            break; 
  
        default: 
            Console.WriteLine("No Flower Selected"); 
            break; 
        } 
    } 
} 

Output:

No Flower Selected
Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp String

  • C# Convert String to Enum
  • C# Convert Int to String
  • Convert a String to Boolean in C#
  • Related Article - Csharp Switch

  • C# Convert String to Enum
  • C# Convert Int to String
  • Convert a String to Boolean in C#