Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

C# | How to use strings in switch statement

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

The switch statement is a multiway branch statement. It provides an easy way to forward execution to different parts of code based on the value of the expression. String is the only non-integer type which can be used in switch statement. Important points:

  • Switching on strings can be more costly in term of execution than switching on primitive data types. Therefore, it is good to switch on strings only in cases in which the controlling data is already in string form.
  • The comparison perform between String objects in switch statements is case sensitive.
  • You must use break statements in switch case.

Example 1: 

CSharp




// C# program to illustrate how to use
// a string in switch statement
using System;
 
class GFG {
     
    // Main Method
    static public void Main()
    {
        string str = "one";
         
        // passing string "str" in
        // switch statement
        switch (str) {
             
        case "one":
            Console.WriteLine("It is 1");
            break;
 
        case "two":
            Console.WriteLine("It is 2");
            break;
 
        default:
            Console.WriteLine("Nothing");
        }
    }
}


Output:

It is 1

Example 2: 

CSharp




// C# program to illustrate how to use
// a string in switch statement
using System;
 
class GFG {
     
    // Main Method
    static public void Main()
    {
        string subject = "C#";
         
        // passing string "subject" in
        // switch statement
        switch (subject) {
             
        case "Java":
            Console.WriteLine("Subject is Java");
            break;
 
        case "C++":
            Console.WriteLine("Subject is C++");
            break;
 
        default:
            Console.WriteLine("Subject is C#");
             
        }
    }
}


Output:

Subject is C#

My Personal Notes arrow_drop_up
Last Updated : 21 Feb, 2023
Like Article
Save Article
Similar Reads