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:
// C# program to illustrate hwo 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"); break; } } } |
chevron_right
filter_none
Output:
It is 1
Example 2:
// C# program to illustrate hwo 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#"); break; } } } |
chevron_right
filter_none
Output:
Subject is C#
Recommended Posts:
- C# Decision Making (if, if-else, if-else-if ladder, nested if, switch, nested switch)
- Switch Statement in C#
- Switch Expression in C# 8.0
- Getting the Total Number of Days in a Month Using If-else and Switch Statements in C#
- C# - if Statement
- C# - if else Statement
- C# - continue Statement
- C# - Break statement
- How to use Array.BinarySearch() Method in C# | Set -1
- C# | How to use multiple catch clause
- C# | How to use Interface References
- How to use Array.BinarySearch() Method in C# | Set -2
- How to use :: Namespace Alias Qualifier in C#
- How to use AcceptsReturn Property of TextBox in C#?
- How to use AutoCheck property of CheckBox in C#?
- C# | Swap two Strings without using third user defined variable
- C# | Get the number of strings in StringCollection
- C# | Remove all the strings from the StringCollection
- C# | Arrays of Strings
- Interpolated Verbatim Strings in C# 8.0
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

