What if you could replace long, messy if-else chains with a neat, powerful one-liner that understands your data?
Why Switch expressions with patterns in C Sharp (C#)? - Purpose & Use Cases
Imagine you have a list of different shapes, and you want to find their areas. Without patterns, you write many if-else statements checking each shape type and calculating the area separately.
This manual way is long, hard to read, and easy to make mistakes. Adding new shapes means adding more if-else blocks, making the code messy and confusing.
Switch expressions with patterns let you match shapes by type and properties in a clean, concise way. You write all cases in one place, making the code easier to read and extend.
if (shape is Circle) { area = Math.PI * ((Circle)shape).Radius * ((Circle)shape).Radius; } else if (shape is Rectangle) { area = ((Rectangle)shape).Width * ((Rectangle)shape).Height; } else { area = 0; }
area = shape switch { Circle c => Math.PI * c.Radius * c.Radius, Rectangle r => r.Width * r.Height, _ => 0 };You can write clearer, shorter code that handles many cases smoothly and is easy to update.
In a drawing app, you can quickly calculate areas or colors of different shapes using switch expressions with patterns, making the app faster to develop and maintain.
Manual if-else chains are long and error-prone.
Switch expressions with patterns simplify matching by type and properties.
Code becomes cleaner, easier to read, and extend.
Practice
Solution
Step 1: Understand switch expressions
Switch expressions allow matching on values or types in a concise way.Step 2: Compare with if-else chains
They replace long if-else chains with clearer, more readable code.Final Answer:
Match values and types cleanly without long if-else chains -> Option CQuick Check:
Switch expressions = clean matching [OK]
- Confusing switch expressions with loops
- Thinking switch expressions handle exceptions
- Believing switch expressions declare variables
Solution
Step 1: Identify correct switch expression syntax
The switch expression syntax is: variable switch { pattern => result, ... }.Step 2: Match options to syntax
var result = obj switch { int i => i * 2, string s => s.Length, _ => 0 }; matches this syntax exactly with type patterns and a discard pattern.Final Answer:
var result = obj switch { int i => i * 2, string s => s.Length, _ => 0 }; -> Option AQuick Check:
Correct switch expression syntax = var result = obj switch { int i => i * 2, string s => s.Length, _ => 0 }; [OK]
- Placing switch before the variable
- Using parentheses instead of braces
- Misplacing the switch keyword
object value = 5;
string result = value switch
{
int i when i > 0 => "Positive integer",
int i when i < 0 => "Negative integer",
string s => "String",
_ => "Unknown"
};
Console.WriteLine(result);Solution
Step 1: Analyze the switch expression input
The variable 'value' is an object holding the integer 5.Step 2: Match patterns in order
First pattern matches int i when i > 0, which is true for 5, so result is "Positive integer".Final Answer:
Positive integer -> Option BQuick Check:
5 > 0 matches first pattern [OK]
- Ignoring the 'when' condition
- Assuming string pattern matches first
- Choosing default case incorrectly
object obj = "hello";
var output = obj switch
{
int i => i.ToString(),
string s => s.ToUpper(),
default => "none"
};Solution
Step 1: Check switch expression patterns
In C# switch expressions, the discard pattern uses '_' not 'default'.Step 2: Identify the incorrect pattern usage
The code uses 'default' which causes a syntax error; it should be '_'.Final Answer:
Using 'default' instead of '_' for discard pattern -> Option DQuick Check:
Discard pattern = '_' not 'default' [OK]
- Using 'default' keyword in switch expressions
- Confusing switch statements with switch expressions
- Forgetting to end statements with semicolon
- "Number" if the object is an int or double
- "Text" if the object is a non-empty string
- "Empty" if the object is an empty string
- "Other" for anything else
Which of the following switch expressions correctly implements this logic?
Solution
Step 1: Understand type patterns and conditions
We must match int or double first, then string with length checks for empty/non-empty.Step 2: Check order and conditions
obj switch { int _ or double _ => "Number", string s when s.Length == 0 => "Empty", string s when s.Length > 0 => "Text", _ => "Other" } correctly checks int or double, then string with Length == 0 for "Empty", then Length > 0 for "Text", then default.Final Answer:
obj switch { int _ or double _ => "Number", string s when s.Length == 0 => "Empty", string s when s.Length > 0 => "Text", _ => "Other" } -> Option AQuick Check:
Order and conditions matter in switch patterns [OK]
- Using 'or' incorrectly without parentheses
- Checking string emptiness with == "" instead of Length
- Placing empty string check after non-empty
Ready to prove it?
Pass the test and this pattern moves unknown
