Seven Things about C#

A beginners tutorial, where each article highlights 7 important things about a specific feature of the C# programming language.

Follow publication

7 Things about C#: Switch Statements

Joe Mayo
Seven Things about C#
6 min readSep 26, 2024

--

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.

A multi-colored chameleon.

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;
}

A switch has a parameter, cases, and logic for each case. Each casehas a value whose type matches the parameter. Although each case has a single Console.Write statement, it could have an entire block of multiple statements.

Tip: Try to limit how much code you add to each case to make it easier to read the switch logic. Calling a single method, if it makes sense, is the cleanest. Who knows, you might be able to reuse code if the case logic is similar.

We’ll discuss the default case and break in the following sections.

2 — The default case is often useful

It’s frequently the case (pardon the pun) that the set of values the user provides falls outside the scope of either what makes sense or what you are prepared to write code to handle. For this, we have a default case, which means that if none of the other cases match, run the default. Here’s an excerpt from the…

--

--

Seven Things about C#
Seven Things about C#

Published in Seven Things about C#

A beginners tutorial, where each article highlights 7 important things about a specific feature of the C# programming language.

Joe Mayo
Joe Mayo

Written by Joe Mayo

Author, Instructor, & Independent Consultant. Author of C# Cookbook: — http://bit.ly/CSharpCookbook — @OReillyMedia #ai #csharp #Web3

No responses yet

Write a response