Switch Statements in C# Language
If you’re a developer or a programming enthusiast looking to level up your C# game, then you’ve
probably heard of, or perhaps even used, the versatile “switch” statement. The “switch” statement is a powerful control structure in C# that allows you to make decisions and choose specific code paths based on the value of an expression. In this post, we’ll explore the various aspects of the “switch” statement in C#, its syntax, and provide some practical examples to help you harness its full potential.Basic “switch” Statement Syntax
Before we dive into examples, let’s understand the basic syntax of the “switch” statement in C#:
switch (expression)
{
case value1:
// Code to execute when expression equals value1
break;
case value2:
// Code to execute when expression equals value2
break;
// More case labels...
default:
// Code to execute when no case matches
break;
}
expression
: This is the value you want to evaluate, and the “switch” statement is based on this value.case
: These are the possible values of the expression you want to compare.default
: This is an optional block of code that is executed when no case matches.
Example 1: Basic “switch” Statement
int day = 3;
string dayName;
switch (day)
{
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
default:
dayName = "Weekend";
break;
}
Console.WriteLine($"It's {dayName} today!");
In this example, we use the “switch” statement to determine the day of the week based on the value of the day
variable.
Example 2: “switch” Statement with Enum
enum Season { Spring, Summer, Autumn, Winter }
Season currentSeason = Season.Summer;
string seasonDescription;
switch (currentSeason)
{
case Season.Spring:
seasonDescription = "Blossoming flowers and mild weather.";
break;
case Season.Summer:
seasonDescription = "Warm days, beach trips, and ice cream.";
break;
case Season.Autumn:
seasonDescription = "Colorful leaves and cozy sweaters.";
break;
case Season.Winter:
seasonDescription = "Snowy landscapes and hot cocoa.";
break;
default:
seasonDescription = "Unknown season";
break;
}
Console.WriteLine($"It's {currentSeason}, which means: {seasonDescription}");
In this example, we use a C# enum to represent seasons and determine the current season based on the currentSeason
variable.
Example 3: “switch” Expression (C# 8.0 and later)
Starting with C# 8.0, you can also use “switch” expressions for more concise code:
int day = 3;
string dayName = day switch
{
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
4 => "Thursday",
5 => "Friday",
_ => "Weekend"
};
Console.WriteLine($"It's {dayName} today!");
This example accomplishes the same task as Example 1 but uses the newer “switch” expression syntax for brevity.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.