Use Strings in Switch Statement in C#

Minahil Noor Mar 21, 2021 Feb 28, 2021 Csharp Csharp String Csharp Switch
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

Related Article - Csharp String

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

  • Multiple Case Switch Statement in C#