DEV Community

Juarez Júnior
Juarez Júnior

Posted on

C# Tip: Pattern Matching with is

Let’s talk about Pattern Matching with is, introduced in C# 7, which allows you to perform type checks and capture the value at the same time, making the code more concise and expressive. See the example in the code below.

public class Program
{
    public static void Main()
    {
        object value = 123;

        if (value is int number)
        {
            Console.WriteLine($"The value is a number: {number}");
        }
        else
        {
            Console.WriteLine("The value is not a number.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

With Pattern Matching with is, you can check if an object is of a certain type and capture that value in a single operation. This reduces the need for repeated casting and eliminates the need to use if-else statements to check object types. Additionally, the code becomes more readable and straightforward, especially when dealing with types that may vary during execution.

This feature is particularly useful in scenarios where you need to make decisions based on the type of an object, such as when working with APIs that return different types of results or processing complex data.

Source code: GitHub

I hope this tip helps you use Pattern Matching with is to simplify type checking in your projects! Until next time.

Top comments (0)