Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to use strings in switch statement in C#
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. In C#, you can use strings directly in switch statements, making it convenient to handle text-based conditions.
Syntax
Following is the syntax for using strings in a switch statement −
switch (stringVariable) {
case "value1":
// code block
break;
case "value2":
// code block
break;
default:
// default code block
break;
}
Key Rules
String comparisons in switch statements are case-sensitive.
Each case must end with a
breakstatement to prevent fall-through.The
defaultcase is optional and executes when no other case matches.String literals must be compile-time constants in case labels.
Using Strings in Switch Statement
Example 1: Grade Evaluation
using System;
public class Demo {
public static void Main(String[] args) {
string grades = "A1";
switch (grades) {
case "A1":
Console.WriteLine("Very good!");
break;
case "A2":
Console.WriteLine("Good!");
break;
case "B1":
Console.WriteLine("Satisfactory!");
break;
default:
Console.WriteLine("Invalid!");
break;
}
Console.WriteLine("Grade = " + grades);
}
}
The output of the above code is −
Very good! Grade = A1
Example 2: Day of Week Processing
using System;
public class WeekdayDemo {
public static void Main(String[] args) {
string day = "Monday";
string dayType;
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
dayType = "Weekday";
break;
case "Saturday":
case "Sunday":
dayType = "Weekend";
break;
default:
dayType = "Invalid day";
break;
}
Console.WriteLine(day + " is a " + dayType);
}
}
The output of the above code is −
Monday is a Weekday
Case Sensitivity in String Switch
Example 3: Demonstrating Case Sensitivity
using System;
public class CaseSensitivityDemo {
public static void Main(String[] args) {
string color = "red";
switch (color) {
case "Red":
Console.WriteLine("Capital R - Red");
break;
case "red":
Console.WriteLine("Lowercase - red");
break;
case "GREEN":
Console.WriteLine("Uppercase - GREEN");
break;
default:
Console.WriteLine("Color not found");
break;
}
// Test with different casing
string anotherColor = "Red";
switch (anotherColor) {
case "Red":
Console.WriteLine("Found: " + anotherColor);
break;
default:
Console.WriteLine("Not found: " + anotherColor);
break;
}
}
}
The output of the above code is −
Lowercase - red Found: Red
Conclusion
String switch statements in C# provide a clean and readable way to handle multiple string comparisons. Remember that string comparisons are case-sensitive, and each case must include a break statement to prevent fall-through behavior.
