C# 9.0: Pattern Matching

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome to this video my name is phillip eckberg and today we'll be talking about improvements made to pattern matching in c sharp 9. before we get into the improvements that have been made to pattern matching in c-sharp i briefly want to cover what pattern matching is i want you to consider that you're looking at a random fruit to determine what fruit it is you can identify its different attributes in programming this would be the property or field values for example is it related to a lemon is it green is it round does it have seeds or is it edible probably not this is effectively defining a pattern to help us match different fruits when we've determined what fruit we are working with we can for example make a lemon pie or lime pie or a banana pancake how does this translate into programming pattern matching isn't really a new concept it's been around for ages and have been a part of programming languages such as f-sharp kotlin and others for a very long time in c-sharp however it's a fairly new language feature and was only first introduced in c sharp 7. although at this point the language feature was rather limited prior to the introduction of pattern matching you might end up writing a code snippet that checks a given type looks at a few different property values and then based on that it would perform some operation with c-sharp 8 things got a lot more interesting and pattern matching was drastically improved not only by allowing us as developers to define patterns that better express the intent of what we're looking for but also help us write less verbose and more readable code if you are already comfortable with pattern matching in c sharp 8 you can skip to the next part of the video where we talk about the improvements that have been made in c sharp 9. in c sharp 8 this is where what's known as the switch expression was first introduced with the switch expression and different types of patterns we can write more compact and readable code and that's truly powerful in essence the switch expression lets you define a code block with a switch keyword sort of like when creating a normal switch however with this each case is a pattern and when the pattern is a match you execute the expression on the right obviously the pattern can consist of checking the type and property values sounds simple it really is in addition to checking the type and property values c-sharp 8 supports three different patterns positional pattern property pattern as well as the tuple pattern the positional pattern requires the object to define what's known as a deconstruct method or if used directly with a tuple there is no need for a deconstruct method the deconstruct method takes the object and allows it to be deconstructed into a tuple with that in mind we can define a pattern that determines if the object is deconstructed into something that matches the criteria of being green has seeds and is edible let's try this again i'd very much argue that this lime here shouldn't be eaten like this if we only care about the collar we can use a discard to ignore the last two values that are passed from the deconstruct method based on its name you probably understand that the position matters when creating this pattern the first value coming out of the deconstruct method is the first value that we are going to match on and so forth optionally you can capture the value that the deconstruct method gives you into a new local variable meaning that we can use this in the expression part the property pattern is for the times when we cannot extend the type with a deconstruct method here is the same code that we just looked at written using the property pattern finally c sharp 8 allows for a tuple pattern this is very similar to the positional pattern with the main difference that the object we match on isn't deconstructed but it is in fact already a tuple ready to hear about the new patterns and the improvements coming in c sharp 9 let's jump straight into it the main goal at this point is to introduce patterns that allow more ways of naturally expressing our intent to do this c-sharp 9 introduces the following six new patterns type patterns conjunctive and patterns disjunctive or patterns negated not patterns parenthesized patterns and relational patterns let's go through each of them and see how they're applied in the language first off we've got the type pattern which by the sound of it allows to check if a variable is a given type we've had ways to do this previously but with the type pattern this becomes a little bit more cleaner previously the type in the pattern had to be followed by either a positional tuple or a property pattern consider the following scenario where we have a base type that represents a test result it's subclassed and we're introducing a positive as well as a negative result we now want to construct a pattern that allows to check if the outcome is positive or negative or inclusive this introduces the type pattern just as with previous versions of pattern matching we can use the discard parameter to match on everything else we could expand on this pattern and apply a recursive pattern much like what we've done in c sharp 8. the change in c sharp 9 though is that we can focus only on the type itself next we'll look at the relational patterns in short what the relational patterns allows you to do is to match your input against constant values to determine if the input is greater than less than or equal to that constant to give this a go we'll make our code a little bit more interesting i'm going to introduce two new properties on the result class that determines if the test result is valid as well as the test date we'll also introduce the deconstruct method remember this is a way for us to take the object and deconstruct it into a tuple which is perfect if we want to use this with pattern matching the deconstruct method will determine how many days it's been since we first submitted the test we can now construct a pattern using the positional pattern much like we saw in c-sharp 8. however we want to say that the test can't be older than 10 days the first position in this tuple is therefore going to define a pattern to check if the value on the tuple's position is greater than 10. simply put this is a pattern to say that the value coming out of the deconstruct method must be greater than the constant we provide given something that we match on we can determine if the value is greater than less than or equal without having to be more verbose isn't this quite handy are you ready for the next pattern let's look at conjunctive and patterns this is just a fancy way of saying that both patterns on either side of an and keyword must match very much like when constructing an if statement that contains the and operator both the sides of the and operator must be true to enter the if block with pattern matching it's the same thing but in this case both patterns on each side of the end keywords must be a match given our current state of the application how about if we'd like to say that the test must be between 10 and 20 days old with the conjunctive and pattern this is easy we can simply add the word and followed by the additional pattern which could be another relational pattern this doesn't only have to be used with a positional pattern or tuples at all for that matter to prove this we can construct a pattern that first uses the type pattern followed by the positional pattern and relational pattern and finally using the property pattern to match on the property that is not exposed by the deconstruct method explaining this is a mouthful but when expressed with a pattern and the pattern matching it's really not that complex this shows how the pattern can be used to chain on additional required patterns that must match obviously the code could become rather hard to maintain if you start writing code like this remember that this just illustrates its capabilities as with any language feature it where it makes sense and where it helps you write more understandable and maintainable code as you might have guessed since we can use the conjunctive and pattern there's going to be a disjunctive or pattern don't worry i'll explain this in plain english it just means that we can use the or operator if we replace the and keyword in our patterns with the or keyword instead this means that if any of these different patterns match it will evaluate the given expression very similar to when you use the or operator in an if statement if you happen to construct a pattern that uses both the and and the or pattern which i'm sure a lot of you will in these scenarios you might also want to use the pattern known as parenthesized patterns this is not only a way to group the patterns but a powerful way to express a requirement consider the following scenario in our application for a positive test result that is still valid and was tested on either 10 or 15 days ago we'd like to send a notification to the tested person we'd also like to send the same notification if the test was tested on exactly 20 days ago but is now marked as an invalid test the issue with the following pattern is that the final or will match on any result that can be deconstructed into this positional pattern this means if we create a negative test with the test state set to 20 days ago and the is valid property set to false this would execute the expression did you expect that given that it works just like an if statement that has the same type of checks using the end and the or operator it might not be a surprise personally i would probably have missed it and this would have been considered a bug in my application to fix this we can wrap the two patterns after the end in parenthesis now we also increased the parenthesized pattern great this now works as expected the final pattern we'll cover is negated not pattern i really don't understand why this one took so long to get into the language how often haven't you had the urge to write something like if x is not my class this pattern isn't only great for checking the type or rather checking that a type is not what you want you can negate absolutely any pattern how about saying that we'd like to check if our test result is not positive or negate the positional tuple we could do that easily using the negated not pattern please just don't do this for the property pattern in this case where we're checking a boolean value it would be so much easier to simply check if each valid is false although i guess that's up to you those were all the new patterns and the improvements in c sharp 9 for pattern matching are you excited about this improvement maybe it's just me that gets excited about these language features i guess anything that helps me write less verbose and more readable code that's also easier to maintain is a really good thing to summarize these are the new patterns we are getting in c sharp 9. type patterns conjunctive and patterns disjunctive or patterns negated not patterns parenthesized patterns as well as relational patterns if you are coming from a different programming language this is maybe not a new concept to you for the rest of us this is a very nice addition to our programming language i'm sure that microsoft has a lot of improvements they want to make to future versions of c-sharp and more patterns to add i guess time will tell and it's really an exciting time to base csharp and net developer i'd love to hear in the comments if there's a pattern that you're missing in the language or if you've already been using pattern matching in your current applications and if it's drastically changed the way that you write your code so please leave a comment and let me know and if you like this video please do feel free to leave a like and subscribe to the channel for more videos in the future you can also check out my courses on pluralsight where i primarily cover c-sharp topics such as asynchronous programming thanks for watching this video my name is phil beckberg and today we've been covering pattern matching in c-sharp 9. you
Info
Channel: Filip Ekberg
Views: 12,409
Rating: undefined out of 5
Keywords: csharp, programming, .NET, C#, Filip Ekberg, dotnet
Id: 9lvx6mzCAE4
Channel Id: undefined
Length: 16min 41sec (1001 seconds)
Published: Thu Oct 01 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.