Pattern matching is awesome

9/27/2022
4 minute read

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

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:

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:

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

How does List work under the hood in .NET?

A List is one of the most used data types in .NET. You can dynamically add elements without taking care of how that happens. But do you know what is going on under the hood?

C# Lowering

Did you ever hear the word "compiler magic" or "syntactic sugar"? Probably yes and therefore we want to dissect what this "magic" really is!

We can see how we can predict performance or bugs by "lowering" our code. Also we will see how things like foreach, var, lock, using, async, await, yield, anonymous types, record, stackalloc, pattern matching, Blazor components, deconstructor, extension methods... do not really exist.

Pattern matching and the compiler can be surprising

Pattern matching is a powerful feature in C#. It allows you to match a value against a pattern and extract information from the value. The compiler does the magic for you - and sometimes it struckles with that.

An error has occurred. This application may no longer respond until reloaded. Reload x