Advanced C# Features: Pattern Matching
Quick Answer
Pattern matching in C# allows developers to check a value against a pattern and extract information in a concise and readable way. It enhances type checking, conditional logic, and data extraction, making code more expressive and maintainable.
Learning Objectives
- Explain the purpose of Pattern Matching in a practical learning context.
- Identify the main ideas, terms, and decisions involved in Pattern Matching.
- Apply Pattern Matching in a simple real-world scenario or practice task.
Introduction to Pattern Matching in C#
Pattern matching is a powerful feature introduced in modern C# versions that simplifies complex conditional logic by matching data against patterns.
It allows you to test types, extract values, and write more readable and concise code compared to traditional if-else or switch statements.
Pattern matching brings clarity and expressiveness to conditional logic.
What is Pattern Matching?
Pattern matching lets you check an object against a pattern and, if it matches, extract information from it.
It is commonly used in switch statements, expressions, and conditional statements to simplify code that depends on the shape or type of data.
- Matches types and values
- Extracts data from objects
- Improves code readability
- Reduces boilerplate code
Types of Patterns in C#
C# supports several pattern types that can be combined for powerful matching scenarios.
- Type Patterns
- Constant Patterns
- Property Patterns
- Positional Patterns
- Var Patterns
- Relational Patterns
- Logical Patterns
Type Patterns
Type patterns check if an object is of a specific type and, if so, cast it to that type for use.
- Syntax: `expr is Type variableName`
- Example: `if (obj is string s)`
Property Patterns
Property patterns match an object based on the values of its properties.
They allow nested matching of properties for more precise conditions.
- Syntax: `expr is Type { Property1: pattern1, Property2: pattern2 }`
- Example: `if (person is { Age: > 18, Name: "Alice" })`
Positional Patterns
Positional patterns match objects based on their deconstructed positional elements, often used with records or tuples.
- Syntax: `expr is Type(var1, var2)`
- Example: `if (point is (0, 0))`
Using Pattern Matching in Switch Expressions
Switch expressions combined with pattern matching provide a concise way to handle multiple conditions.
They replace verbose switch statements with expressive, functional-style code.
- Use `switch` keyword with patterns
- Supports all pattern types
- Returns values directly from cases
Example: Shape Area Calculation
Calculate the area of different shapes using a switch expression with pattern matching.
Practical Example
Checks if obj is a string and extracts it to variable s.
Matches a person object with Age greater than 18 and Name equal to Alice.
Matches a point tuple at the origin (0,0).
Uses switch expression to identify shape types and extract properties.
Examples
object obj = "Hello";
if (obj is string s)
{
Console.WriteLine($"String length: {s.Length}");
}Checks if obj is a string and extracts it to variable s.
if (person is { Age: > 18, Name: "Alice" })
{
Console.WriteLine("Adult named Alice");
}Matches a person object with Age greater than 18 and Name equal to Alice.
if (point is (0, 0))
{
Console.WriteLine("Origin point");
}Matches a point tuple at the origin (0,0).
string GetShapeType(object shape) => shape switch
{
Circle c => $"Circle with radius {c.Radius}",
Rectangle r => $"Rectangle {r.Width}x{r.Height}",
_ => "Unknown shape"
};Uses switch expression to identify shape types and extract properties.
Best Practices
- Use pattern matching to simplify complex conditional logic.
- Prefer switch expressions for multiple pattern cases.
- Combine patterns for precise matching.
- Use property patterns to avoid nested if statements.
- Leverage positional patterns with records and tuples.
Common Mistakes
- Using pattern matching without null checks leading to exceptions.
- Overcomplicating patterns when simpler conditions suffice.
- Ignoring the default case in switch expressions.
- Misusing var patterns causing unclear code.
Hands-on Exercise
Implement a Shape Area Calculator
Use pattern matching with a switch expression to calculate the area of Circle, Rectangle, and Triangle classes.
Expected output: Correct area values for each shape type.
Hint: Use property and type patterns to extract dimensions.
Filter a List of Objects
Write a method that filters a list of objects using property patterns to select only those with specific property values.
Expected output: Filtered list matching the criteria.
Hint: Use the 'is' keyword with property patterns inside a LINQ Where clause.
Interview Questions
What is pattern matching in C#?
InterviewPattern matching in C# is a feature that allows checking an object against a pattern and extracting information if it matches, improving code readability and expressiveness.
Name three types of patterns supported in C#.
InterviewType patterns, property patterns, and positional patterns.
How does a switch expression differ from a traditional switch statement in C#?
InterviewSwitch expressions return values and support pattern matching, making them more concise and expressive compared to traditional switch statements.
MCQ Quiz
1. What is the primary advantage of using pattern matching in C# over traditional if-else statements?
Select one option to check your answer.
2. Which pattern type in C# allows you to match an object based on the values of its properties, including nested properties?
Select one option to check your answer.
3. Given the code snippet: if (obj is string s) { Console.WriteLine(s.Length); } What pattern type is being used here?
Select one option to check your answer.
4. How do positional patterns in C# typically match objects?
Select one option to check your answer.
5. What is a key benefit of using switch expressions combined with pattern matching in C#?
Select one option to check your answer.
Key Takeaways
- Pattern matching in C# allows developers to check a value against a pattern and extract information in a concise and readable way.
- It enhances type checking, conditional logic, and data extraction, making code more expressive and maintainable.
- Pattern matching is a powerful feature introduced in modern C# versions that simplifies complex conditional logic by matching data against patterns.
- It allows you to test types, extract values, and write more readable and concise code compared to traditional if-else or switch statements.
- Pattern matching lets you check an object against a pattern and, if it matches, extract information from it.
Frequently Asked Questions
Which C# version introduced pattern matching?
Pattern matching was introduced in C# 7.0 and has been enhanced in subsequent versions.
Can pattern matching be used with null values?
Yes, but you should handle null cases explicitly to avoid exceptions.
What is the difference between property and positional patterns?
Property patterns match based on object properties, while positional patterns match based on deconstructed positional elements like tuples or records.
Summary
Pattern matching in C# is a versatile feature that enhances code clarity and reduces boilerplate.
By mastering type, property, and positional patterns along with switch expressions, developers can write more expressive and maintainable code.
Applying best practices and avoiding common mistakes ensures effective use of pattern matching in real-world applications.





