Pattern Matching in C#
Introduction
Pattern matching is a powerful feature in C# that allows you to test if a value has a certain shape and extract information from it if it does. This feature enhances the readability and maintainability of the code by providing a more expressive syntax for complex conditional logic.
Basic Pattern Matching
Pattern matching in C# can be used in various contexts, such as is
expressions, switch
statements, and more. Let's start with a simple example using the is
expression:
Example:
object obj = "Hello, World!"; if (obj is string str) { Console.WriteLine($"The string is: {str}"); }
In this example, we check if obj
is a string. If it is, we assign it to the variable str
and print it.
Switch Pattern Matching
The switch
statement has been enhanced to support pattern matching. This allows for more concise and readable code when dealing with multiple conditions.
Example:
object obj = 42; switch (obj) { case int i when i > 40: Console.WriteLine("The number is greater than 40."); break; case string s: Console.WriteLine($"The string is: {s}"); break; default: Console.WriteLine("Unknown type."); break; }
In this example, we use pattern matching in a switch
statement to handle different types and conditions for the variable obj
.
Property Pattern Matching
Property pattern matching allows you to match on the properties of an object. This is useful when you need to check the properties of an object and take action based on their values.
Example:
var point = new { X = 1, Y = 2 }; if (point is { X: 1, Y: 2 }) { Console.WriteLine("Point is at (1, 2)."); }
In this example, we check if the properties X
and Y
of the point
object match the specified values.
Tuple Pattern Matching
Tuple pattern matching allows you to match on tuples. This is useful when you need to handle multiple values together.
Example:
var tuple = (1, "Hello"); if (tuple is (1, "Hello")) { Console.WriteLine("Tuple matches (1, 'Hello')."); }
In this example, we check if the tuple values match the specified pattern.
Positional Pattern Matching
Positional pattern matching allows you to deconstruct an object and match its values. This is particularly useful for types that support deconstruction.
Example:
var person = new Person("John", "Doe"); if (person is Person(string firstName, string lastName)) { Console.WriteLine($"Person's name is: {firstName} {lastName}"); }
In this example, we use positional pattern matching to deconstruct the person
object and match its values.
Conclusion
Pattern matching in C# provides a concise and readable way to handle complex conditional logic. From basic type checks to more advanced property and positional patterns, it enhances the expressiveness of your code.