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

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

7
Buy Me a Coffee at ko-fi.com
An error has occurred. This application may no longer respond until reloaded. Reload x