DEV Community

Alex Dhaenens
Alex Dhaenens

Posted on

What the hell is property pattern matching?

I'vealready made some posts about pattern matching, with the last one about positional pattern matching. Pattern matching made it possible to do a type check, cast to that checked type into a variable and then deconstruct its properties into variables:

if (person is Elf(int age, string elfishName))
            {
                Console.WriteLine($"Elf with elfish name{elfishName} is {age} years old");
            }
Enter fullscreen mode Exit fullscreen mode

And it made it also possible to do a value check while deconstructing:

if (person is Elf(110, string elfishName))
            {
                Console.WriteLine($"Elf with elfish name{elfishName} is 110 years old");
            }

Enter fullscreen mode Exit fullscreen mode

One of the drawbacks of this technique is that a deconstructor is needed (more about that in my blogpost about object deconstructing). Luckely for us, C# 8.0 provides us with property pattern matching!

What is it?

Well property pattern matching does the same as positional pattern matching but without the need of a _Deconstructor_ . The code above, which checks if the person is an Elf then deconstructs it and checks if his/her age is 110, looks like this with property pattern matching:

if (person is Elf{ Age: 110, ElfishName: var elfishName })
            {
                Console.WriteLine($"Elf with elfish name{elfishName} is 110 years old");
            }
Enter fullscreen mode Exit fullscreen mode

As you can see, the syntax is quite similar to its counterpart. The downside however, is that it is more (computationally) expensive.

Sources

https://docs.microsoft.com/en-us/dotnet/csharp/deconstruct
Demo project: https://bitbucket.org/aldhaenens/p-d-demo/src/master/

Top comments (0)