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
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp String

  • Remove a Character From a String in C#
  • Count Occurrences of a Character Inside a String in C#
  • Related Article - Csharp Switch

  • Repeat String X Times in C#
  • C# Convert Int to String