How to Use Switch Case in C#
Using "If...else" throughout your C# application can be hard to read and may also lead to you making programming mistakes. Instead use a "switch" statement that selects a switch section to execute from a list of candidates. A switch statement contains switch sections with one or multiple case labels that match the value of a switch expression. A switch expression is the value to be matched with a case label and when the match is made the code following the case section will execute.
Instructions
-
-
1
Launch Microsoft Visual C# Express and click "New Project." Click "Visual C#" below "Installed Templates" and double-click "Console Application" to create a new console application.
-
2
Copy and paste the following code to check a constant value with a switch expression:
int switchVal = 6;
Console.WriteLine("First switch example:");
switch (switchVal)
{
case 1:
Console.WriteLine("This is case 1");
break;
case 6:
Console.WriteLine("This is case 6");
break;
default:
Console.WriteLine("Default case");
break;
}
-
-
3
Copy and paste the following code to check a switch expression using more than one case label:
Console.WriteLine("-----------------------");
Console.WriteLine("Second switch example:");
int switchValSecond = 2;
switch (switchValSecond)
{
case 1:
case 2:
Console.WriteLine("This is case 1 and 2.");
break;
case 3:
Console.WriteLine("This is case 3");
break;
default:
Console.WriteLine("Default case");
break;
}
-
4
Add the following code to check a String expression using String values in the case labels:
Console.WriteLine("-----------------------");
Console.WriteLine("Third switch example:");
string switchValThird = "7";
switch (switchValThird)
{
case "1":
case "2":
Console.WriteLine("This is case 1 and 2.");
break;
case "7":
Console.WriteLine("This is case 3");
break;
default:
Console.WriteLine("Default case");
break;
}
-
5
End the program by adding the following lines of code:
Console.WriteLine("-----------------------");
Console.WriteLine("Press any key to end program...");
Console.ReadKey(true);
-
6
Press "F5" to run your program.
-
1
References
- Photo Credit Ablestock.com/AbleStock.com/Getty Images