switch Expressions
Concise value-returning switches.
switch Expressions is a free C# Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is a switch Expression?
A switch expression evaluates an input against a series of patterns and returns a value. Unlike the classic switch statement, it is an expression, so it produces a result you can assign or return.
It uses the switch keyword after the value, with arms written as pattern => result. This makes branching logic compact and functional.
int code = 2;
string name = code switch
{
1 => "One",
2 => "Two",
_ => "Other"
};
System.Console.WriteLine(name);Statement vs Expression
The old switch statement uses case labels and break. The newer switch expression drops those keywords entirely.
Arms are separated by commas, the whole thing ends with a semicolon, and each arm yields a value rather than executing fall-through blocks. This removes a whole class of forgotten-break bugs.
// Statement style
switch (code) { case 1: result = "One"; break; }
// Expression style
result = code switch { 1 => "One", _ => "?" };The Discard Arm
The underscore _ is the discard pattern. It matches anything and acts as the default case.
Switch expressions must be exhaustive: if no arm matches at runtime, a SwitchExpressionException is thrown. Adding a _ arm guarantees a match for every possible input.
using System;
class Program {
static void Main() {
int n = 7;
string size = n switch {
< 5 => "small",
_ => "big"
};
Console.WriteLine(size);
}
}Constant Patterns
The simplest arm uses a constant pattern: a literal value the input is compared against using equality.
Constants can be numbers, strings, characters, enum members, or named constants. They are evaluated top to bottom, so order the most specific or most common arms first.
char grade = 'B';
string label = grade switch
{
'A' => "Excellent",
'B' => "Good",
'C' => "Fair",
_ => "Needs work"
};
System.Console.WriteLine(label);Returning From a Method
Switch expressions shine inside methods. Because the whole construct is an expression, you can return it directly, often as a single-line expression-bodied method.
This keeps mapping logic readable and centralized instead of scattering if/else if chains across the body.
using System;
class Program {
static string Day(int d) => d switch {
0 => "Sun", 6 => "Sat", _ => "Weekday"
};
static void Main() => Console.WriteLine(Day(6));
}Switching on Enums
Enums pair naturally with switch expressions. Each arm names an enum member, and the compiler can warn when a case is missing if you omit the discard arm.
Still, keeping a _ arm is wise so future enum values do not crash your app at runtime.
using System;
enum Light { Red, Yellow, Green }
class Program {
static void Main() {
Light l = Light.Green;
string action = l switch {
Light.Red => "Stop",
Light.Yellow => "Slow",
Light.Green => "Go",
_ => "?"
};
Console.WriteLine(action);
}
}Guard Clauses with when
A when guard adds a boolean condition to an arm. The arm matches only if both the pattern and the guard are true.
This lets you refine matches with arbitrary logic that a pattern alone cannot express, such as range checks combined with other variables.
int temp = 30;
string weather = temp switch
{
int t when t < 0 => "Freezing",
int t when t < 20 => "Cool",
_ => "Warm"
};
System.Console.WriteLine(weather);Order Matters
Arms are tested in source order. The first matching arm wins, so more specific patterns must come before broader ones.
If a general arm precedes a specific one, the compiler reports the later arm as unreachable. Read your arms top to bottom like a funnel from narrow to wide.
int score = 95;
string tier = score switch
{
>= 90 => "Gold",
>= 70 => "Silver",
_ => "Bronze"
};
System.Console.WriteLine(tier);Exhaustiveness and Exceptions
If every input is not covered and no arm matches, the runtime throws System.Runtime.CompilerServices.SwitchExpressionException.
The compiler emits warning CS8509 when it cannot prove exhaustiveness. Treat that warning seriously: add a discard arm or cover the missing values to keep the expression total.
using System;
class Program {
static void Main() {
try {
int x = 5;
string s = x switch { 1 => "a", 2 => "b" };
Console.WriteLine(s);
} catch (Exception e) {
Console.WriteLine(e.GetType().Name);
}
}
}Combining Multiple Inputs
To switch on more than one value, wrap them in a tuple. The arms then match tuple patterns, comparing each position.
This is ideal for state machines or decision tables where the result depends on a pair of factors. We will explore tuple patterns in depth in a later lesson.
bool isWeekend = true; bool isRaining = false;
string plan = (isWeekend, isRaining) switch
{
(true, false) => "Go hiking",
(true, true) => "Watch a movie",
_ => "Work"
};
System.Console.WriteLine(plan);Readable Expression Bodies
Switch expressions compose well with LINQ and expression-bodied members, producing concise pipelines.
Because each arm returns a value, you can use a switch expression directly inside a Select projection or as a method argument, avoiding temporary variables.
using System;
using System.Linq;
class Program {
static void Main() {
var nums = new[] { 1, 2, 3 };
var labels = nums.Select(n => n switch {
1 => "one", 2 => "two", _ => "many"
});
Console.WriteLine(string.Join(",", labels));
}
}Quick Check
Test your understanding of switch expressions.
Recap
Switch expressions return a value using input switch { pattern => result, ... } with comma-separated arms.
Use _ for the default, when for guards, and remember arms are tested top to bottom. Keep them exhaustive to avoid runtime exceptions. Next we explore type and property patterns.
Frequently asked questions
Is the “switch Expressions” lesson free?
Yes — the full text of “switch Expressions” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “switch Expressions”?
Concise value-returning switches. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “switch Expressions” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.