Seven Things about C#

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

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.

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

--

--

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