Exploring the Power of Pattern Matching in C#

Dima Pursanov
3 min readAug 14, 2024

--

Pattern matching in C# has evolved significantly over the last few versions, becoming one of the most powerful and expressive features in the language. This feature enables developers to write cleaner, more concise, and more readable code by allowing you to check a value against a pattern and perform actions based on that match.

What is Pattern Matching?

Pattern matching in C# allows you to test an object against a specific pattern and, if it matches, extract values and execute code accordingly. It’s akin to a more powerful switch statement or if checks but with much more flexibility.

Key Benefits

1. Type Safety: Pattern matching ensures type safety by allowing you to work with the matched type directly without the need for explicit casting.

2. Conciseness: Reduces the boilerplate code often associated with multiple if-else or switch statements.

3. Expressiveness: Allows for more expressive code by supporting complex patterns like tuples, positional patterns, and even recursive patterns.

Practical Example

Let’s look at a practical example using pattern matching to process different shapes:

public abstract class Shape {}
public class Circle: Shape {
public double Radius {
get;
set;
}
}
public class Rectangle: Shape {
public double Length {
get;
set;
}
public double Width {
get;
set;
}
}
public class Triangle: Shape {
public double Base {
get;
set;
}
public double Height {
get;
set;
}
}
public double CalculateArea(Shape shape) =>shape
switch {
Circle c =>Math.PI * Math.Pow(c.Radius, 2),
Rectangle r =>r.Length * r.Width,
Triangle t =>0.5 * t.Base * t.Height,
_ =>
throw new ArgumentException("Unknown shape", nameof(shape))
};

In this example, the CalculateArea method uses a switch expression to determine the type of shape and calculate its area accordingly. Each case in the switch expression checks the type of the `shape` object and matches it with the appropriate pattern. This approach is not only clean but also easy to extend if you introduce new shapes in the future.

New Features in C# 9 and Later

With the release of C# 9, pattern matching has become even more powerful with the introduction of relational patterns and logical patterns:

- Relational Patterns: Match a value based on its relation to another value (e.g., `<`, `<=`, `>`, `>=`).

public string DescribeNumber(int number) =>
number
switch {
<
0 => "Negative",
0 => "Zero", >
0 => "Positive"
};

- Logical Patterns: Combine patterns using logical operators like `and`, `or`, and `not`.

public bool IsTeenager(int age) => age is >= 13 and <= 19;

Conclusion

Pattern matching in C# is a feature that brings both simplicity and power to your code. By using pattern matching, you can make your code more readable, reduce the need for explicit type checks, and take advantage of C#’s rich type system. If you haven’t yet explored pattern matching in depth, now is a great time to start incorporating it into your projects!

--

--

No responses yet