Pattern Matching in C#: Simplifying Type Checking and Data Analysis

Learn about pattern matching in C#, a concise and readable way to perform type checking and data analysis. This guide explains how to use pattern matching with `is` expressions and `switch` statements, improving code clarity and reducing complexity.



Pattern Matching in C#

C# pattern matching provides a concise and readable way to perform type checking and data analysis on objects. It improves code clarity and helps avoid cumbersome `if-else` chains or `switch` statements.

The `is` Expression

The `is` expression checks if an object is compatible with a given type. If it is, it returns `true`; otherwise, `false`. It's a more readable alternative to using `typeof` or casting and checking for nulls.


if (myObject is MyClass myInstance) {
    // Access members of myInstance
}

If the object is of type `MyClass`, the variable `myInstance` is created and holds the object; otherwise, the code within the `if` block is skipped.

Example 1: Type Checking with `is`


public class Person { public string Name { get; set; } }

public class Example {
    public static void Main(string[] args) {
        object person = new Person { Name = "Bob" };
        if (person is Person p) {
            Console.WriteLine(p.Name); // Output: Bob
        }
    }
}

Pattern Matching in `switch` Statements

C# allows pattern matching within `switch` statements. You can check the type of an object and extract its properties simultaneously. This makes `switch` statements much more powerful.


switch (myObject) {
    case Student s:
        // Handle Student object
        break;
    case Teacher t:
        // Handle Teacher object
        break;
    default:
        // Handle other types
        break;
}

Example 2: Pattern Matching in a `switch`


public class Student { public string Name { get; set; } }
public class Teacher { public string Name { get; set; } public string Subject { get; set; } }

public class Example {
    public static void Main(string[] args) {
        // ... (code to create Student and Teacher objects, then call PatterInSwitch) ...
    }
    // ... (PatterInSwitch method) ...
}