C# Control Statements: Pattern Matching Tutorial
Quick Answer
Pattern matching in C# allows you to test an expression against a pattern and extract information in a concise way. It enhances control statements like if, switch, and is, making your code more readable and expressive.
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 C# 7.0 that simplifies type checking and conditional logic.
It allows you to test an expression against a pattern and, if it matches, extract data from it in a concise and readable way.
This tutorial covers how to use pattern matching within control statements to write cleaner and more maintainable C# code.
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 with the 'is' keyword and switch statements to simplify type checks and value comparisons.
- Simplifies type checking and casting.
- Improves readability by reducing nested if-else statements.
- Supports various pattern types like type patterns, constant patterns, and property patterns.
Using Pattern Matching with 'is' Expressions
The 'is' keyword can be combined with a pattern to check an object's type and simultaneously declare a variable.
This eliminates the need for explicit casting after a type check.
- Syntax: `if (obj is Type variableName)`
- The variable is only in scope inside the if block.
Example: Type Pattern with 'is'
This example checks if an object is a string and prints its length.
Pattern Matching in Switch Statements
Switch statements support pattern matching to handle complex conditional logic more elegantly.
You can match types, constants, and even properties within switch cases.
- Supports type patterns, constant patterns, and property patterns.
- Enables more concise and readable code compared to traditional switch-case.
Example: Switch with Pattern Matching
This example demonstrates a switch statement that matches different shapes and calculates their area.
Common Pattern Types in C#
C# supports several pattern types to match different scenarios.
- Type Pattern: Matches the type of an expression (e.g., `obj is string s`).
- Constant Pattern: Matches a constant value (e.g., `x is 5`).
- Property Pattern: Matches properties of an object (e.g., `point is { X: 0, Y: 0 }`).
- Var Pattern: Always matches and captures the value (e.g., `var x`).
Practical Example
This example checks if 'obj' is a string and prints its length using pattern matching with 'is'.
This switch statement uses pattern matching to identify the shape type and calculate its area.
This example uses a property pattern to check if a point is at the origin.
Examples
object obj = "Hello, World!";
if (obj is string s)
{
Console.WriteLine($"String length: {s.Length}");
}This example checks if 'obj' is a string and prints its length using pattern matching with 'is'.
public abstract class Shape { }
public class Circle : Shape { public double Radius { get; set; } }
public class Rectangle : Shape { public double Width { get; set; } public double Height { get; set; } }
Shape shape = new Circle { Radius = 5 };
switch (shape)
{
case Circle c:
Console.WriteLine($"Circle area: {Math.PI * c.Radius * c.Radius}");
break;
case Rectangle r:
Console.WriteLine($"Rectangle area: {r.Width * r.Height}");
break;
default:
Console.WriteLine("Unknown shape");
break;
}This switch statement uses pattern matching to identify the shape type and calculate its area.
public class Point { public int X { get; set; } public int Y { get; set; } }
Point p = new Point { X = 0, Y = 0 };
if (p is { X: 0, Y: 0 })
{
Console.WriteLine("Point is at the origin.");
}This example uses a property pattern to check if a point is at the origin.
Best Practices
- Use pattern matching to reduce explicit casting and improve code readability.
- Prefer switch expressions with pattern matching for concise conditional logic.
- Use property patterns to match complex object states clearly.
- Keep pattern matching expressions simple to maintain readability.
Common Mistakes
- Overusing pattern matching in complex expressions leading to hard-to-read code.
- Forgetting that variables declared in pattern matching have limited scope.
- Using pattern matching where simpler conditional statements would suffice.
- Not handling default cases in switch statements with pattern matching.
Hands-on Exercise
Implement Shape Area Calculator
Create a switch statement using pattern matching to calculate areas of different shapes: Circle, Rectangle, and Triangle.
Expected output: Correct area calculations printed for each shape.
Hint: Use type patterns in the switch cases and extract necessary properties.
Use Property Patterns
Write an if statement using property patterns to check if a Point object is on the X-axis (Y=0).
Expected output: Message confirming the point lies on the X-axis.
Hint: Use the syntax `if (point is { Y: 0 })`.
Interview Questions
What is pattern matching in C#?
InterviewPattern matching in C# is a feature that allows checking an expression against a pattern and extracting information if it matches, simplifying type checks and conditional logic.
How does pattern matching improve code readability?
InterviewIt reduces the need for explicit casting and nested if-else statements by combining type checking and variable declaration in a concise syntax.
Name some pattern types supported in C#.
InterviewType patterns, constant patterns, property patterns, and var patterns.
MCQ Quiz
1. What is the best first step when learning Pattern Matching?
A. Understand the purpose and basic idea
B. Skip directly to advanced implementation
C. Ignore examples and practice
D. Memorize terms without context
Correct answer: A
Starting with the purpose and basic idea makes later examples and practice easier to understand.
2. Which activity helps reinforce Pattern Matching?
A. Reading once without practice
B. Building or writing a small practical example
C. Avoiding review questions
D. Skipping the summary
Correct answer: B
A small practical example helps connect the topic to real usage.
3. Which statement is most accurate about this topic?
A. Pattern matching in C# allows you to test an expression against a pattern and extract information in a concise way.
B. Pattern Matching never needs examples
C. Pattern Matching is unrelated to practical work
D. Pattern Matching should be learned without checking results
Correct answer: A
The correct option is based on the available topic explanation.
Key Takeaways
- Pattern matching in C# allows you to test an expression against a pattern and extract information in a concise way.
- It enhances control statements like if, switch, and is, making your code more readable and expressive.
- Pattern matching is a powerful feature introduced in C# 7.0 that simplifies type checking and conditional logic.
- It allows you to test an expression against a pattern and, if it matches, extract data from it in a concise and readable way.
- This tutorial covers how to use pattern matching within control statements to write cleaner and more maintainable C# code.
Summary
Pattern matching in C# enhances control statements by simplifying type checks and conditional logic.
It supports various pattern types like type, constant, and property patterns, enabling concise and readable code.
Using pattern matching effectively leads to cleaner, more maintainable C# programs.
Frequently Asked Questions
Which C# version introduced pattern matching?
Pattern matching was introduced in C# 7.0.
Can pattern matching be used with switch expressions?
Yes, pattern matching works seamlessly with switch expressions for concise conditional logic.
What is a property pattern in C#?
A property pattern matches an object based on the values of its properties.
What is Pattern Matching?
Pattern matching in C# allows you to test an expression against a pattern and extract information in a concise way.
Why is Pattern Matching important?
It enhances control statements like if, switch, and is, making your code more readable and expressive.
How should I practice Pattern Matching?
Pattern matching is a powerful feature introduced in C# 7.0 that simplifies type checking and conditional logic.

