loading...

What the hell is property pattern matching?

alexdhaenens profile image Alex Dhaenens ・1 min read

Seeing sharp (4 Part Series)

1) What the hell is pattern matching? 2) What the hell is object deconstructing? 3) What the hell is positional pattern matching? 4) 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");
            }

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");
            }

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");
            }

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/

Seeing sharp (4 Part Series)

1) What the hell is pattern matching? 2) What the hell is object deconstructing? 3) What the hell is positional pattern matching? 4) What the hell is property pattern matching?

Posted on by:

alexdhaenens profile

Alex Dhaenens

@alexdhaenens

I'm a full stack software engineer & interested in all engineering things. But I'm really, really, passionate about software

Discussion

markdown guide