Pattern matching
Functional pattern matching in C# is a technique that’s used to match the structure of data against a series of patterns and execute specific code blocks based on the matched pattern. It allows developers to express complex conditional logic in a more concise and declarative way, making code more readable and maintainable.
In C#, functional pattern matching can be achieved using the switch
statement with the case
pattern matching feature that was introduced in C# 7.0. With this feature, you can pattern match on various types, constant values, or even custom patterns using the when
keyword.
Here’s an example of functional pattern matching in C#:
public 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; } } public class Triangle : Shape { ...