Member-only story
7 Things about C#: Switch Statements
In an earlier article about If Statements, we covered the common scenario where you’ll need to run specified logic based on a unique condition. During that discussion, we clarified why you might want to branch based on a condition and the same rationale applies to switch
statements. One of the first differences, from if
, is that the condition of a switch
statement is a value, rather than a conditional expression. This article explains how to use switch
and the scenarios in which it excels.
1 — Ideal for one of many conditions
Sometimes you want to get input from the user where that input represents a set of values. From that set of values, you might want to run a separate algorithm that is unique to that value. You can certainly do that with an if/else
statement. However, check out the game show example below to see how switch
is uniquely designed for this scenario:
Console.Write("Which door? (1, 2, or 3): ");
string doorResponse = Console.ReadLine();
switch (doorResponse)
{
case "1":
Console.Write("You chose the first door.");
break;
case "2":
Console.Write("You chose the middle door.");
break;
case "3":
Console.Write("You chose the last door.");
break;
default:
Console.Write("Sorry, door #" + doorResponse + " doesn't exist.");
break;
}