Published on

Pattern Matching in C# 7: Simplifying Code and Enhancing Flexibility

Overview

Pattern matching is a powerful feature introduced in C# 7 that allows developers to write more concise and expressive code. It simplifies the process of checking data types, properties, and other conditions, making code more readable and maintainable. In this article, we will explore the pattern matching capabilities in C# 7 and understand how it enhances flexibility and productivity.

1. Understanding Pattern Matching:

Pattern matching is a technique that enables developers to check if an object or expression satisfies a certain pattern. It allows for matching and extracting values based on their shape, structure, or properties. Prior to C# 7, achieving such behavior required multiple if-else statements or type casting, making the code verbose and error-prone.

C# 7 introduced a simplified syntax for pattern matching, making it easier to handle common scenarios. It leverages the is keyword to check if an object matches a specific pattern and introduces the switch statement to perform pattern matching on multiple cases.

2. Using Pattern Matching with is:

The is keyword in C# 7 allows developers to check if an object matches a particular type or pattern. It returns a boolean value indicating the result of the pattern matching operation. Let's consider an example:

object data = "Hello, World!";

if (data is string text)
{
    Console.WriteLine($"The data is a string: {text}");
}

In this example, the is keyword checks if the data object is of type string and assigns the matched value to the text variable. If the pattern matching is successful, the code block inside the if statement is executed.

3. Pattern Matching in switch Statements:

Pattern matching in switch statements is another powerful feature introduced in C# 7. It allows developers to match patterns against different cases and execute specific code blocks accordingly. Consider the following example:

public static string GetShape(Shape shape)
{
    switch (shape)
    {
        case Circle c:
            return $"Circle with radius {c.Radius}";
        case Rectangle r:
            return $"Rectangle with width {r.Width} and height {r.Height}";
        case Triangle t:
            return $"Triangle with base {t.Base} and height {t.Height}";
        default:
            return "Unknown shape";
    }
}

In this example, the switch statement performs pattern matching on different cases, including Circle, Rectangle, Triangle, and the default case. The variables c, r and t capture the matched values, allowing access to their specific properties.

4. Combining Pattern Matching with when:

C# 7 introduced the when clause, which allows developers to apply additional conditions to pattern matching. It enables more precise matching based on property values or complex expressions. Let's consider an example:

if (data is string text && text.Length > 10)
{
    Console.WriteLine($"The text is a string with length greater than 10: {text}");
}

In this example, the when clause combines a type pattern with a condition. It checks if the data object is a string and its length is greater than 10. If the condition is satisfied, the code block is executed.

5. Pattern Matching with null and var:

Pattern matching in C# 7 also provides convenient ways to handle null values and var patterns. The null pattern can be used to check if an object is null, and the var pattern allows for declaring implicitly typed variables. Here`s an example:

object data = null;

if (data is null)
{
    Console.WriteLine("The data is null.");
}

var value = data;

switch (value)
{
    case null:
        Console.WriteLine("Value is null.");
        break;
    case int intValue:
        Console.WriteLine($"Value is an integer: {intValue}");
        break;
    case string stringValue:
        Console.WriteLine($"Value is a string: {stringValue}");
        break;
    default:
        Console.WriteLine("Unknown value");
        break;
}

In the first part, the is keyword is used to check if the data object is null. If the condition is true, it executes the code block inside the if statement.

In the second part, the switch statement performs pattern matching on the value object. The null pattern is used to check if value is null, and the var pattern is used to declare implicitly typed variables for matching integer and string types.

6. Conclusion:

Pattern matching in C# 7 is a powerful feature that simplifies code and enhances flexibility. It allows developers to write more concise and readable code by reducing the need for complex type checks and explicit casting. The is keyword and switch statement make pattern matching easier to use and understand. Additionally, the when clause, null pattern, and var pattern provide further flexibility in handling conditions and variable declarations.

By leveraging pattern matching in C# 7, developers can improve code quality, reduce the chance of errors, and enhance their productivity. It enables cleaner and more expressive code, making it easier to maintain and extend applications.

Remember to explore the official C# documentation and experiment with various pattern matching scenarios to deepen your understanding and proficiency in this powerful feature.