---
title: "Pattern matching is awesome"
description: "Pattern matching, which was introduced in C# 9, is a hell of a beast and does more than you might think.\n\nIn this small blog post I show you where the magic is and what it does under the hood."
updated: 2022-09-27
tags: ["C#", "Infographics", ".NET"]
canonical: "https://steven-giesel.com/blogPost/d411dc5c-5618-43b2-9b60-8385e50647a3/pattern-matching-is-awesome"
---

# Pattern matching is awesome

Pattern matching, which was introduced in C# 9, is a hell of a beast and does more than you might think. Often times you see the `is` keyword in connection with `null` and in direct contrast to `==` operator. And yes there **can be** a difference between `is null` vs `== null` and that is precisely when your class override the `==` operator. `is null` will **always** check against a null reference, where as `== null` will do this most of the times.

Another funny side note is, that you can't use `is null` with value types like `int`, `double`, ... because they can never be `null`. On the contrary `== null` can be true depending on how `==` is defined. 

## Pattern matching
See the two code snippets, with pattern matching it automatically checks whether or not your give instance is null.

![Pattern Matching 1](https://linkdotnetblog.azureedge.net/blog/20220927_PatternMatching/PatternMatching.webp)

But not only that, it also checks whether or not your child properties are null if you use the extended property matching introduced with C# 10:

```csharp
void Check(Parent? p)
{
    if (p is { Child: {Age: >18}})
         Console.WriteLine("Something");
}

record Parent(Child Child);
record Child(int Age);
```

Will be translated into:
```csharp
void Check(Parent p)
{
    if ((object)p != null)
    {
        Child child = p.Child;
        if ((object)child != null && child.Age > 18)
        {
            Console.WriteLine("Something");
        }
    }
}
```
So it is save to pass in `null` without getting any NullPointerException.

## Type-interferences

Another neat detail is that `is` takes the runtime type into consideration. In the code below you see two times the same signature but the outcome is different.

![Pattern Matching 2](https://linkdotnetblog.azureedge.net/blog/20220927_PatternMatching/PatternMatching2.webp)