DEV Community

Nick
Nick

Posted on

Mastering Pattern Matching in C#

Pattern matching is a powerful feature in C# that allows developers to identify specific patterns in data structures such as objects, arrays, or tuples. By using pattern matching, developers can easily extract and manipulate data in a more concise and readable way.

One common use case for pattern matching is in switch statements, where developers can use patterns to match specific cases and execute corresponding code blocks. Let's take a look at a simple example of pattern matching in a switch statement:

public void ProcessData(object data)
{
    switch (data)
    {
        case int number:
            Console.WriteLine($"Received an integer: {number}");
            break;
        case string text:
            Console.WriteLine($"Received a string: {text}");
            break;
        default:
            Console.WriteLine("Received an unknown type");
            break;
    }
}
Enter fullscreen mode Exit fullscreen mode

In the code snippet above, the switch statement uses patterns to match different data types (int and string) and execute the corresponding code blocks. This allows for more concise and readable code, as developers can easily identify the different patterns that the data can match.

Pattern matching can also be used with advanced patterns such as object patterns, tuple patterns, and property patterns. Here's an example of using property patterns to extract data from an object:

public void ProcessEmployee(Employee employee)
{
    switch (employee)
    {
        case { Name: "John", Age: 30 }:
            Console.WriteLine("Found employee John, age 30");
            break;
        case { Name: var name, Age: var age }:
            Console.WriteLine($"Found employee {name}, age {age}");
            break;
        default:
            Console.WriteLine("Employee not found");
            break;
    }
}
Enter fullscreen mode Exit fullscreen mode

In the code snippet above, we use property patterns to extract the Name and Age properties from the Employee object and match specific values. This allows for more flexible and expressive patterns, making it easier to work with complex data structures.

Overall, mastering pattern matching in C# can greatly improve the readability and maintainability of your code. By using patterns to identify and extract specific data, developers can write more concise and efficient code that is easier to understand and maintain.

Top comments (0)