5 New Features in C# 9 (not including Records)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
c sharp 9 is out and there are a bunch of new features but do we really need them just because they're new doesn't make them valuable so in this video we'll be looking at five new features we'll identify how to use each and then talk about where they are useful as well as where they are not we won't be covering records in this video because they deserve their own video which comes out in a couple of days now if this is the first video you've watched of mine my name is tim corey and it's my goal to make learning c-sharp easier i provide videos twice a week here on youtube to help you grow as a developer i also have a full set of training courses on iamtimcory.com and i'd encourage you to check out all the resources i have to offer in this video as with most of my videos i'm going to create some source code if you'd like a copy of my source code use the link in the description so let's get started looking at these new features now here i have visual studio open and it's important to note that i have visual studio version 16.8.1 there's actually a minor or actually a a bug fix release that's been out since 16.8 came out so if you go to help about if yours looks similar to this 16.8.1 you'll be able to follow along also note that this is visual studio community edition 2019 so community edition is free as long as you fall into a few general categories for personal use or even small business use so just note we'll be using community edition all right so file let's start a new our new start window and the first feature we're going to look at is top level calls so i'm going to create a a new project we'll create a console application so console.net core application that's is a c sharp application if you're not filtering by c-sharp then you make it vb or f-sharp and so on so make sure you're filtering by the language you want to use at least now i call this project name console ui because we're going to have a couple different projects in this solution so the solution name will be new dot net features or let's actually say new c sharp features to be clear here because these are c-sharp nine features these are features of the language itself there's also net five features which are something different it's a little confusing sometimes but the language is c sharp and we can use different ides to work with a language including just a text editor but then there's dot-net which is kind of the underlying uh frameworks and that usually entails things like templates and so on and we'll look at some of those features uh later on in a couple of a couple more days at least if you get confused which one is a c-sharp 9 feature versus a.net 5 feature versus a visual studio 16.8 feature don't worry you're not alone it's okay it's not the end of the world to make sure you know which when it comes in just make sure that you get this feature so with that let's hit create and let's talk about these top level calls so in a console application we have a bit of ceremony around starting a a console and if you're familiar consoles at all and you should be if you've worked at c sharp at all then you know that the compiler looks for when it creates the executable file it looks for this class program and it looks for static void main and this is the entry point for your application this is where your application starts in fact this clear brace is the start of your code and this clear brace right here indicates the application is done and it closes the application but if you notice we have 12 lines of code for one line of actual code and before we go any further i do want to point out this cool little addition right here it says value colon this is something new in visual studio it's not part of c sharp knives part of visual studio um in the this version i might keep saying 16.8 but it's in there so i do want to point this out because i think this is helpful this is an inline hint let me create one more method trust me this is relevant to the whole thing but i'm going to say uh private static void add int x int y and we're going to say return x plus y really simple addition method right well we can make a call here oops not stag void in and they should be doubles that's what i get for going fast right so static void double it's going to return a double it's going to add two double together so if i said uh let's just do a console right line let's just call the add method and say 4 and 3. well now it shows me that this 4 is the x value and the y is or is three so that shows with a parameter names are it's a little hint that is just kind of bonus how does this do this how we get this feature because if you're doing it you probably don't see it in your copy of visual studio so i do want to point out there's a lot of little things that have been added recently and so as you know i don't want to create a whole video around just this but i'll point these out as we go so good tools options now options in here is a ton of great stuff that you can use now as collapse down environment because we actually want to go to the text editor which is right down here and find your language in this case we're working with c sharp notice all the languages that are in here really cool stuff you can do with all of those but in c sharp under advanced and in here if you scroll down there's going to be a display inline parameter name hints that's this right here this is experimental so this is something that is just barely in visual studio you have to enable it if you want to see it but with this we now get these really cool hints that allow us to see hey what was that parameter name oh that's the x parameter because we have two numbers here if you have that turned off then you see add four and three and you don't know is for the x or is for the y and now x and y aren't terribly descriptive but if we had better names we'd see um better uh parameters here to kind of tell us what's going on so really cool stuff there but in this particular case the first thing we're going to look at is these top level top-level calls so we have a ceremony and now we have even more ceremony but but for really two lines of code here and another couple lines of code here we have 18 lines maybe we can do better than that so what if we did this what if we took away the curly braces around main and took away a stack void man itself and maybe class program as well and maybe even name space console ui got rid of the whole thing and then got rid of these closing curly braces as well and this is now top level code except the fact that it's yelling me all over so it's saying hey you can't do top level statements these are not available in c sharp eight and you say yeah but c sharp nine is out how do i apply c sharp nine well you right click on console ui and go to properties and you see that oh target framework is dot net core 3.1 let's change as a dotnet five now this is a good time to talk about dotnet versus.net core this is some there's some confusion here that we'll make sure we're clear on dotnet five does not include dotnet framework so dotnet framework was at 4.8 that's the last level it hit before we moved to net core we will not be including dot net framework going forward there is no merger of net framework and net core dot net core is the way forward now with net core since there's a they're dropping.net framework mean that does not mean they stop support they will support net framework 4.8 as long as windows is supported but we know new features all new features in net will be in dot-net itself so you see core to differentiate itself from that framework but now that moving forward we're past framework we're not talking about it anymore we're not using it with new features anymore so now we have just.net 5. so this is the continuation of net core 3.1 it's the next iteration they skipped 4 because they didn't want to have confusion between net framework for and dot net for so let's kind of skip that entirely now it's net five dot net five going forward will be the unified platform now you may have heard of maui and i've even had people ask me recently hey you're gonna show off maui maui doesn't exist yet maui will come about in.net six that is next year november 2021 is when it will be officially released the intro versions and early release versions of that coming out in a few months but for the actual production ready stuff not until november 2021 unless of course plans change so the move from net core 3.1 to net 5 is not a big deal in a lot of cases it's just that i hit save i close it and now we're good to go so i can clean this up a bit let's go ahead and delete private and let's shift tab this to move it back to the the right indentation level and let's talk about what's happening here because this isn't quite the same thing is what i had originally let's even go back to what i had let's see if we can um there we go so that's the original let's actually well let's talk the original and then let's talk about the the difference okay so in the original let's see if we can get actually i can just do control z right nope i can't let's go to the original let's talk what we had so in the original we had the static void main and they had a a method in the same class we can't really have that if we have a top level call but if you know let's private off for a minute if you were to cut this out and paste this right there that works now what i just do i just put a method inside of a method you may say tim well how does that even work well that's a local method that's a method that only works inside of the main method these can be useful once in a while especially if you're going to do a couple of different additions in here but you don't want to create a whole method that is externally available because it's only really for this method that's why you might use a local method well we talk about having our our top level code we can't really have other methods inside of this this uh file so we really make them make them local methods or put them in a different file so the end result is getting rid of all of this and getting rid of all of this and now we have top level code and let's just prove this works by running console ui because it looks weird right we have hello world and seven so it is working but how is it working because there's no namespace there's no class there's no method how does it know to call this well what the what c sharp 9 does is it says that if you have a class file which program.cs this file right here if you have a file that has top level calls meaning there is no namespace there is no class there is no method it's just code then that is assumed to be the entry point of your application so it's taking some of the ceremony away from creating an initial console application now the question may come up yeah but why would you do that and the answer is we don't have to you can still do an uh the original console application with the namespace the class the method name that's all cool do it that way it's fine but this way if you want to create something quicker and easier and less ceremony and less curly braces indenting in and out you can do it this way now like i showed this method right here looks like it might be accessible from other places but if you notice i had private and yelled at me let's make it public and it's going to yell at me here as well because the modifier public is not valid for this item because you can't have a modifier on a local method a local method only works inside that local piece instead of that local area so in your top level call file you can only have the code that would go inside the static void main method that's it nothing else you can have your local calls like the add method if it's only going to be inside the static void main and you can have as much code in here as you want as long as it would normally fit inside static void main that's it you're using statements still work you can still do that you can still even reorder these things if you want as long as they're all gonna act as though they're in static void main now there is an exception to that i would encourage you not to take advantage of the exception but the exception is if you want to put code below your top level calls you want to say public public class person model or whatever something like that you can do this that still works because your your top level call is it at the top but if you were to say you know what i want to move this to be above the top level call well no you can't do that that's no longer valid code if you have non-top-level calls above your top level call so just remember top-level calls need to go at the top so that's that's the the top-level calls now there is a question that may come up that um and by the way again just don't put our class in here don't do that have just your one top level call be basically static void main that's it nothing else but the question may come up like it did for me well how does a compiler actually find this it's probably pulling some kind of trick where it looks for program.cs the file right and the answer is no it's not in fact if we right click and say add new class and let's call this demo.cs and first of all let's just prove let's grab this exact same code i'm gonna copy it i'm gonna paste it into demo and save it and it says nope only one compilation unit can have top level statements so we've got a problem we can't have both of these files and i say okay aha i've proven you have to have it in program.cs well no you don't because if i right click on program.cs and i hit delete then we're cool it still runs and if we execute it we still get the hello world and seven so it's not about which file it's in it's not about you know it's only about having top level code in one place if the compiler finds top level code somewhere in your application doesn't matter where it is it's going to say gotcha that's the starting point of your application so it's going to grab the top level calls until you hit something like uh public class person or whatever once it hits something like that then it's going to stop and say okay now on line 10 that's the end of your application meaning your application is now going to close so that's how top level calls work let's talk about when you would use this or why even have it i think the biggest thing around having top level calls is just the simplicity and the removal of ceremony and with console apps especially we're talking about applications that might be used for things like microservices or maybe we have a hundred of these well if we have a lot of these having a lot less ceremony just makes sense if it's only going to be a few lines of code that it's doing then why have all this extra ceremony just because and even if you're creating small console applications to do something if you have everything crammed into your static void main you should probably shouldn't but if you do then you can eliminate a lot of those indents you don't need you have three levels of indent with namespace and class and method that you can get rid of and have three less curly braces to keep track of so it makes life a little simpler simple is usually better when it comes to programming because simple means less things that can go wrong now if you're just learning c sharp i would encourage you not to go down this road yet because this doesn't really give you the picture of how a normal c-sharp application works you saw how it could only have one top level call everyone else has to have the namespace the class and the method name so this is just a shortcut i encourage you to learn the full way of doing things first and get used to that because that's the way you're going to do it normally so why don't you not use this well notice there's no place to send in parameters so normally in a a console application we have a place to pass in our args so if you have a command line switch you can pass in those command line arguments we don't have that here so therefore you're missing that if you need those then you need a full the full call not this top level code call instead so that's one place to use again if you're a new developer i would encourage you to go the full route instead but otherwise doesn't hurt anything and in a lot of ways it saves some time and effort and it makes your code simpler to read and understand i would just make sure that if you have you know class person model that you move that into its own file what you can do with ctrl dot when you're on the name and go down to rename file to personnel dot see it that's not right no let's not do that it renamed demo in a person model i think they what i did was i had a a rename right there but normally if you control dot you can extract this into its own file but it looks like with top level code you can't do that so that's just another reason why avoid using a class with top level code instead right click add class person model and then move your code over here which in this case i had no code so i can just get rid of it here but now i have my top level code in one file you shouldn't call it demo you should call it program.cs because that is the place that is universally looked at as the starting point of your application this just proves you don't have to do it that way but notice how clean that is now we have one place for let's i'm just gonna rename this because it's driving nuts program.cs it's just the starting point of your application but now we have just our program.cs has just top level code lot less ceremony it's very very clean it does just we need it to do and in fact we can get rid of this code here well i'll leave it there for for demo purposes so you can see it later but again remember this is a local function but the next we're going to look at is going to be the next new feature of c sharp 9 that is is going to be init setters so let's look at person model for a minute and we're going to say let's do int id and then we'll have first name and last name so this is a typical class this class is a model which means essentially it's designed to carry data around together so it carries id first name and last name together in one bundle now again we're going to talk about records in the next video and we'll talk about if this is better to be a class or a record um hint it's not going to be just a record normally there's only certain times when i would convert this to a record but um in this class over here program.cs let's just say that we had a person model ctrl dot to add the using statement notice that we have to add a user thread for console ui why because we don't have a namespace in this top level code so therefore we're not even in the console ui namespace there's no way of calling this code outside of this this top level code which of course is fine because you never call your static void main from other locations so why does it need a namespace so anyways let's just say person model p equals new person model i'm going to say that id equals 1 first name equals tim and last name equals corey cool so that's my new person model and i can use it to do things like well let's do console write line and say let's do our string interpolation which is a dollar sign in front of the um the two double quotes and we'll say hello and we'll say uh p dot first name space p dot last name and then let's put in parens or parentheses whereas say p dot id like so so we'll know the id of the person as well and let's just run this real quick just to see what it says it should be very clear hello tim corey and the id of one that's our our really cool application right now but what if we wanted to protect this id because you know usually we get a information from a database you you have the id number you have the the data so let's just say you're pulling from the person table and database we said okay this is record number one which that's something you can't change that's something that should be basically read only but this data here we could potentially update and we could call back and do an update into our database and say hey the first name you know it was um tim but now is timothy perfectly acceptable normally and you do your you know your your simulated update but what if we said p dot id equals two well that makes a different record in the database maybe that record's actually sue storm but now since i changed the id now sue's record's gonna say timothy corey and that doesn't make sense so we we want a way to change this to say hey you can't you can't change the id number well we do have the option of saying that id is a private set cool but then we have some problems here because we can't put that here we can't put that here and say okay well i'll create a constructor that passes and there's other parameters that works but what if there was a better way because you see let's just say we're using dapper to get our information from our database we need to allow dapper to write to all the fields but we wouldn't want to be able to then change id dapper doesn't play well with calling constructors that's not the way it should work so it's going to work more like this well let's change now to the init property so instead of a private set we're going to say init and what init means is that you can change this value this id value either in a constructor or when you first create the object notice right here that will allow the change of the id but now i cannot change it after the fact so when i first create the record whether it's this way or by constructor that's fine but after that it's read only it's read only not only in this top level method or a different method it's also read only in this class so i can't even create a class or a method let's just say i said uh public void update id and in here i said let's just pass in the id new id and i said id equals new id and it goes no you can't do that because it's a knit only property which means it can only be assigned in object initializer or on the this or base of an instance constructor or the init accessor so you can't do this here now you can if i said ctor i can pass in let's just say int id i can say id equals id that works just fine because this is a constructor it can do that but you can't do it in another method once it's been set it is now read only that's it that also means if you decide not to set the value you're out of luck because now we obviously can't do this here if we run this we can't we can't change that value so now it's zero so that's not ideal we need to make sure that we always set the value either in a constructor or when we create the record but once we do that now that is initialized and it can no longer be changed so that's init setter that's allows us to replace the set of a property with init instead and now you can only access that or change that in the constructor or when the object is being initialized now for me personally that's a huge deal i love that feature because just in in ids alone that makes total sense for me to have that and i will use that a lot it's not quite the same thing as private set which allows you to change that value as long as you're doing it inside the class it's just like i said it's a read only once you've said it initially i love that feature i think it's gonna be great i don't see a downside to having this as an option now obviously you wouldn't want to use this all the time on every property because that would lock everything you read only there is an exception to that though and we'll talk about that in the next video when we discuss records because records it makes a lot more sense to use the init only for every property and we'll talk about why that is but this is a great new feature i think it's it's gonna be one that really allows you to kind of make your applications a little more secure a little more bug proof bug proof being a relative term of course you can still introduce bugs but it's it prevents more bugs and it really expresses your wishes more clearly in code rather than having some type of unwritten rule that people have to follow because unwritten rules don't always get followed so i really like the um the init property now there's one other i i want to illustrate right here there's another feature of of c sharp nine that it's a quick one but it's one that i think is again a quality of life thing it makes a little more sense you know here in this line right here i have a duplication i have person model p equals new person model we don't have to have this duplication now one option we have is to say var because we know what type p is going to be because we're initially assigning it and so it says okay it's a new person model therefore p is notice i mouse over and it says person model and that's fine but some people don't like var and especially when you're newer i don't either because it's harder to read you have to actually go over to here to find out what the type is but this is repetition we're saying person model and person model and it's not a big deal if you have person model but if you have i innumerable of person model now it's a really long thing you've got duplicate on one line and so if the type is readily understood you don't have to have the type name anymore if in this case so i can say just new so person model equals new actually no you can't so the reason that's yell at me is because i'm not using constructor i am assign initial values let's do it again where i say person model p2 equals new person model like so and i can pass in values to this constructor but now i can say equals new like that so as you can see that really cut down on the code i needed because it's inferring the type in the new because we've already specified that the type over here we'll have to say it again in this way unlike var we see on the left what the type is and like i said let's just create constructors over here so i'll create one that's empty so that my code still works from before but now let's create another one where we pass in int id string first name and string last name like so we can say id equals id first name oops first name equals first name and last name equals last name that might be a typical constructor and again remember i'm still using the init property still cool with that because this is a constructor but over here i could even say one let's let's do two because we already have one uh two su and storm and notice with my my tags now it says oh the id is two the first name is sue the last name is corey so it knows how to read this line and this line doesn't have to say new person model because we said person model already so that's just a shortening of that declaration it makes a lot of sense as long as you know the type if i said var here that's not going to fly because there's no target type for new doesn't know what we're talking about you have to give it the type person model and now okay and it does this now again like i pointed out you know when i try to show you this way you can't just delete this because that's not using the constructor that's using the um you know the set of values with the curly braces it doesn't work this way yet so let's undo that now if you still want to use the curly braces to set the values and you didn't want to use a type what you can do is you can put your open and close parens and say use the empty constructor but then set these values and that does work so typically we don't use the constructor when we're saying the values directly using the curly braces but with this type of call without specifying the name you have to use the curly or i'm sorry parens even if you're using the curly braces so that makes things a little easier and it makes things a little shorter and and yet it's still clear what we're doing here with our new so when we use this syntax i think all the time alpha is a reason not to i think this is it's kind of like var it's another tool in our toolbox to make our lives a little easier whether you like the var uh way of doing things or whether you like to specify the the full type just because you specify the full type doesn't mean you can't get the benefits you get with var of having a shorter call because now you can say the full type and then just say yeah create a new version of that and it says okay i know what the type is you don't need to tell me again i already know so that's what this is i don't see a downside to using this i don't think it makes the code unreadable because again your type is right here so you already know the only time it might become a little unreadable is let's just say we had something like this person model p3 these are horrible names by the way but they're short so personal p3 and then maybe even let's go down here in our code just pretend for a minute that's a scroll off the page and i say p3 equals new like that it goes cool i can do that that i'm not a big fan of because yes you can do it that way but now your code is more unreadable these scroll down through okay p3 first of all horrible name person who do that stop it but then you go what is that again all your mouse over go oh it's a person model class gotcha okay so p3 is personal gosh we can keep going from there but don't do that if you're going to have it not be connected with the type i would highly recommend you still say new person model and just be clear that way it's it's easily identifiable as a person model so i think that's the only time i see a real downside is when you do something like that where you don't see the type specified on that same line i like having the type specified here and then not having to specify again i like that lack of repetition i think it's easy i think it's going to make the um you know make your lines shorter and yet still readable but i don't like it when you're doing this and separating out the new down here and not specifying the type down here so that's my personal feel remember again code is meant to be read by humans and your code will be read more often than as written you write it once you read it a lot of times therefore make sure you optimize so it's readable and that means not doing that so i'm going to comment this out and say don't do this let's capitalize to you in this okay and i'll uncover that since i'm saying don't do this um so you're very clear what that's about so that is the the new way of doing new where we don't have to know what the type is since we've already specified the type on the left now for these next two so those are those are the three covered so far um but now for the next two those three are uh top top level initialization which we're using right here and then the the init instead of set and then finally omitting the type when you have a new if it's known what that type is so those are the first three that kind of jumped out at me um that i thought would be actually useful in a lot of situations in c sharp nine now his next two i want to create a new project for now i'm going to create a new project because it's being a lot quicker to do than to try and build some code on the fly for you so let's go a new project and we're going to create a new blazer app now really cool stuff in blazer and let's just call this blazer app i'm adding this to my solution by the way so we'll have two in here we'll switch over to this being a startup project let's go to net core 5.0 notice the drop down here blazer server app we're not going to do authentication we are going to do https not docker hit create and there are some really cool things in blazer that i'm going to cover a whole separate video because there's a lot of cool stuff going on in blazer that i think it's really important to cover in its own video but i want to use let's close all of these why use blazer because it already has some pre-built code for us to demo so let's right click on blazer and say that i want to set a startup project and let's run this just to see what the basic startup project looks like you've probably seen it already a dozen times or more if you play the blazer at all that's okay i just want to point out one thing that's fetch data so fetch data says okay there's a temperature in celsius temperature in fahrenheit i'm from the us so i am much i much easily more easily relate to fahrenheit even though it's a not nearly as cool system as celsius is but if we look here for this weather forecast 57 degrees fahrenheit 14 degrees celsius it says it's scorching well that's not true and 24 degrees is bracing yes it is 48 degrees is scorching no it's not in 105 degrees fahrenheit 41 degrees celsius is not balmy i don't like these they don't correlate in any way to our temperatures now this is just randomly assigned in fact we go back to counter come back here notice all the summaries have changed negative three fahrenheit or have 20 celsius is not mild i am i really love hot weather that's not mild that's awful that's cold that's frigid so these don't correspond to the temperatures in any way in fact if we go back here and look at our data and weather forecast service we come down here to our we get our i innumerable which is a new way of forecast it creates it creates a random value for the temperature in celsius which then gets converted to fahrenheit so that fahrenheit and celsius values are actually in sync so you can look at one ensuite the other would be but then the summary is a random value of one of these things up here so it has no relation at all to our temperature i would like to change that so we're going to do some quick editing to this method this method is all in line it does all the work on the return we're gonna have to break that out so we're gonna do is let's grab this right here and cut it out and say var um var results equals and we'll come down here and we'll say return task from results results and we have our two uh or actually our like so and then we can get rid of that um close paren so now we're doing we've broken this out at two steps first get the results put it into a weather forecast array which that's what this is creating right here and then once we have that array then return that array wrapped inside of task.form from results which what that does is it basically tricks the system into thinking that it's an asynchronous return now with asynchronous typically we return a task and that task says i'll let you know when the code is done working in the background and when it's done working it says oh okay here's the results i'm complete now here's the results of that call well and that's where we get the the weather forecast array is that results the task is a thing that says hey it's still working or it's done well task dot from results basically takes any result set wraps in a task that says yeah it's already done and here's the results so it kind of tricks you into thinking it's asynchronous when really it's just returning the value with a completed task so the reason they did that is because they're simulating calling an api or something else which you'd do asynchronously and so they made it asynchronous call but since it's just random data there's no reason for it to be asynchronous because it's already done it's it inline it's super fast therefore was pretend it's asynchronous so that's what they're doing here that's the microsoft template we're not gonna have to get into it too much more but i am going to change some values here so this summary right here we can actually drop that off of the the initialization because we're going to modify it ourself we're going to create a and this is not this code is not the way i would necessarily do it going forward but this is a demo code to show you this new features so i'm going to do a for each for each var wreck in records oops results so one record in result i call it rack just because i want to keep it short as possible i don't want to have to go and name it something really long so i'll loop through every result in the result set now obviously i could have done this all in one section but i want to keep this code clean and separate because this is the code we're going to show off the new stuff in pattern matching there's two different types of pattern matching that i want to show and so we're going to do that in this section so we're going to first look at pattern matching that's called relational pattern matching this is where we have i'll i'll put it in a comment right here so relational pattern matching is the greater than the less than the greater than or equal to the less than or equal to so those are relational patterns now notice that we don't say equal to or greater than because equal to or greater than would be our arrow function so we don't do that it's always the greater than first or the less than first and then the equal to so these are relational patterns how we use this in here well if i was going to loop through every result and change that summary i would probably say if rack dots not summary wrecked i'm going to deal with fahrenheit because i know fahrenheit a whole lot better than i know celsius so just bear with me if you're if you're used to celsius these numbers might not make sense it's just for dental purposes so if record dot is let's say less than zero then i'm gonna say rack dot summary equals uh well below freezing why because in fahrenheit 32 degrees is freezing so zero is 32 degrees below that freezing line and i would keep going through this i could say okay else if and i'd keep going down all my different different ways of expressing this to see my different ranges but that's really complicated so instead we can say is rec dot summary equals rec dot temperature f switch what this is going to do this is already built into c sharp before c sharp nine we'll do this type of switch statement on a pattern but there's new patterns for this type of switch statement so i'm going to do is say that the value that i'm going to return from this switch statement is going to go into summary and it's based upon degrees temp or temperature fahrenheit so another way of saying this would be if i said uh switch on let's just say that it was temp fahrenheit i can't well here let's get rid of that let's do it right if i were to say switch on wreck dot tempo degrees fahrenheit and then i said you know let's just say that it's zero case zero oops i would say okay then rec dot summary equals you know uh well below freezing break like so but that's a lot of ceremony and it doesn't deal well with what about between you know greater than zero and less than 30 or greater than zero and less than or equal to 32. doesn't deal with that so that's not the best way of doing it because it's just too much ceremony so instead we've got this switch statement which is going to return a value it's going to return a value into summary so we have summary equals and this is what it's based upon so okay the temperature and fahrenheit that's where relational patterns come in if it's less than zero do your arrow and say well below freezing and then we have to have some way of covering all the rest of the cases so we have this this discard pattern the underscore and say it's anything else we'll say unknown we just don't know so right now i've said hey if the temperature's below zero then say it's well below freezing otherwise say unknown but either way notice i'm just saying the arrow function i'm giving a value that value gets put into summary this less than sign now is a relational pattern that says all right you're saying the temperature in fahrenheit is less than zero if it's less than zero then do this think of this as our nested if statements with our else ifs so if it's less than zero then do this else this is our else right here do this so let's create a couple more a couple more options here where we say you know what let's just do if it's 32 we're gonna say um exactly freezing comma notice there's not even a value in front of me that says exactly 32. cool we can do that and we can also say you know what um if it is greater than or equal to 85 then we're going to say hot per comma so now there's another relational pattern greater than or equal to cool we can do that so that's relational patterns it allows us to basically do the equivalent of if else if else if else but we can do so in a very compact manner if all we're trying to do is set the value of one item one variable in this case summary but that brings up the next pattern type which we're going to cover the fifth thing we're gonna cover in c sharp nine i really like and that is our logical patterns and the logical pattern matching is and or let's put ampersand here because that's our third value is not so and or and not are our three pattern matching for logical pattern pattern matching because you know what we're gonna do with ranges here we don't really have a great way of doing ranges unless we have some way of of just using an else as our only range option everything else is kind of limited here what we can do instead is say well if it's greater than or equal to using our relational pattern greater than actually just greater than no greater than or equal to because we haven't included zero greater than or equal to zero let's actually put a number there zero and less than 32. we're going to say freezing so now we have this and here just like you would in an if statement but we type out and it's not the double ampersand and the reason why is they want to differentiate between our if statement and how we do if statements and why that is i'm not entirely certain but i do like using the word and instead of double ampersand you still have to use a double ampersand in if statements but this way it's very clear for pattern matching what this is saying if it's greater than equal to 0 and it's less than 32 what is that it the temperature in fahrenheit so now i can put a few more things in our range where we say okay after 32 we can say greater than or equal to um let's do actually let's just do greater than 32 you already have 32 and we'll say and less than 65 degrees is in my mind cool and then if it's greater than or equal to 65 and less than 85 then again my mind is gonna be warm so now we have some um some different matches here and we can say i think it covers most the spectrum but maybe we could even be a little you know a little more exact you want to could say hey you know what let's do 32 and a hundred and twelve we wanted to i'm sorry 212. we say exactly freezing or boiling whoops not and ha ha see us yell at me because it says that pattern is unreachable because the fact that you can't have 32 and 212 in the same value but if i said or so now you probably wouldn't say this because you'd probably have one for freezing one for boiling but i'm trying to demonstrate that you can do these two values you can use the or keyword which allows you to have this relational pattern i'm sorry this logical pattern but now notice too that we can move all of these around because there are none that would conflict with each other meaning i can have this be the first one in the list if i wanted to move it right up to the top it's ugly right there but not a problem because of the fact that it covers even though it's going to find the first one that applies this only applies for this range now if you were to put something at the very top let's say greater than negative 212 arrow livable something like that notice how we get these these red squigglies because these aren't gonna be covered because we already have covered everything we've said hey if it's greater than negative 212 it's livable but notice if it's less than zero meaning this won't get hit unless it's negative 212 or below because we've already covered native 211 and above but now with these two it says you know what these aren't needed so our system is really good in making sure we don't step on each other's toes that we don't have something that can't be reached because we have written it out of possibility so really cool stuff with this the the editor is really good at understanding how to read all of these at design time and figure out what you need to know about them but this is now our relational pattern so we have our relational patterns here and we have our logical patterns here so let's just run this and before we do it actually notice you can probably see it but the squiggly here is under the discard character because this pattern is unreachable it's already been handled by a previous arm of a switch statement or it's impossible to match because we have greater than or equal to 85 is hot therefore we can even get rid of our our discard pattern because there's no need for that that that last case statement that last option which is the catch-all because we've already caught it all we've got less than zero we've got greater than or equal to 85 and there's no gaps in anywhere in here therefore we don't need that discard pattern so let's run this again and let's see if we have better values for our for our summaries so yeah fetch data and now notice cool is 55 whereas 66 is starting to feel warm 42 is cool uh 125 yeah that's hot 127 that's hot we can keep coming back here and see if we get different values well below freezing at negative two yep that's true negative 19 celsius in case you're wondering um we can keep coming back you'll eventually get that exactly on freezing or boiling right there exactly freezing or boiling because you have 32 degrees so really cool stuff you can do that make this summary a whole lot more understandable rather than having those those random values assigned to it we did all of that with just some pattern matching in this switch statement i'm sorry switch expression it's one of those things a switch statement is where you have switch on you know some kind of value this is a switch statement this is a switch expression because it returns a value that we can then use so that's the difference switch statement let's just and this down here is a switch expression i'm doing all because i'm gonna um be giving you the source code it's down in the description you can um you just fill out your email address it'll email you the a copy of the source code yes you are paying with your email address i rarely email my mailing list it's usually maybe twice a month they'll send you an email and just you know there is a sale coming up that mailing list people get they get exclusive sales so um you might want to stay on it but if you don't want to no problem unsubscribe right away the first email you get and you know no no hard feelings so but with that source code you'll get all of this you can try it all out with my code and you know kind of play around with this new stuff because i encourage you whenever you learn something new try it and try it just like i've done it i have not made a logical application that does something that's where people get hung up a lot as they say well how do i test how do i you know try out what i've learned i don't know what to build and the answer is you don't have to build anything this isn't really anything i mean yeah i had you know something that was pre-built in the temple that i could kind of take advantage of but that's all i'm doing is just kind of taking advantage of that and doing something with it if you want to test something else with pattern matching you could still use the same um the same list or or create your own sample list but those are the five new features of c sharp nine i thought you should see i think there's a lot of value in all of them um i do i mentioned that switch statements can be really helpful in these kind of cases where it really cuts down your code so yes there is some value but you're not going to use this everywhere you're not going to see thousands of switch statements or i'm sorry switch expressions all over the place but when you do need them really really helpful and those patterns are important oh and one thing i forgot it's actually my favorite thing in c sharp nine favorite thing i can't believe i almost forgot it uh i want to say the best for last because this is okay this is me being a little bit of a a geek here but i think this is the best thing to come out of c sharp in a long time so let's go back to our console let's set it as the startup project again and let's go back to program.cs we have this code here now we have a couple different objects here so normally we do you have code like this if p3 is null then console writeline that says the value of p3 is not yet set something like that cool we're we're kind of used to that we don't actually have to assign a value to it because we only assign a value um actually no but there we go so if p3 is null then we say we haven't assigned a value to it and we could do an else that says you know console writeline um let's actually do this this hello statement okay oops come on paste there we go so that's that's we do normally we do a null check first and say hey it's not yet set and then do this but what if we didn't want to have this section here what if we just want to wrap this whole thing and say hey you know what as long as not null go ahead and print this line well what we used to have to do if we took this out here let's actually copy this because i want to keep this as what we used to do let's copy this unless instead of using p3 let's use p 2 which we do know is set we don't want to have this right here so we'd say well actually what you do is uh not equal to no so if p2 is not equal to null then go ahead and write out hello sue storm that's kind of ugly because we're reading it as if p2 is not null so if we just said not and that doesn't work but would we actually ever read it as p2 not null we would probably say is up here we said is null so what if we said is not null well now that reads great and my squigglies went away because this is now a pattern remember not is one of our our patterns when we talked about um our matching up here so we have the ability to say not we didn't use that down here we could have but we do have that option as well with our null is not null i think this is awesome so instead of saying again not equal to null we can say is not no and it reads like it's english and so it's a whole lot easier to read our code it's a little thing it's a tiny tiny little thing but i think it's probably the best thing in c sharp nine the ability to say if p2 is not null that just for me it makes my code so much more readable and remember code is meant to be read by humans it's getting read a whole lot more than it's written so to be able to say is not null just makes so much sense so that's kind of the last thing i want to show you when it comes to these five features just to recap we had that the top level calls we had init setters we had relational patterns we had logical patterns we had the get rid of the new um the type after new and you know using this is not null it's part of our logical pattern but really is for me a whole separate thing that just makes my life so much better when it comes to writing code i'll use this all the time so those are the five like i said we're not covering records in this video because records deserve a whole another video we've already gone an hour into this video and you know we've got a lot to cover when it comes to records about when to use it when not to use them so you'll see that in the next video but that's it for now get the source code down below in the the description get it try it out test out what you learned test out how it works see what does work what doesn't work make sure you understand how to type these things out you know so for me uh forgetting to put the is you know that's just because i'm not yet used to typing it out and i'm almost not used to replacing it not equal but um so get used to it get your fingers used to saying is not null and that way you'll be more set to use this in production and not have errors you've already seen the errors when you create in test so try it all out let me know down in the comments what your thoughts are on these five and if there's anything else besides records and besides these five that may you want to see me cover for net i'm sorry for c sharp nine specifically we'll cover a lot of stuff with net five and with visual studio 16.8 in the upcoming videos there's a lot still to come and if you want to check out the original video in this series where i talked about kind of the overview of what we're covering and what i won't necessarily touch on but is in there um and i want to check that out just kind of see what my thoughts are there so thanks for watching and as always i am tim cory [Music] [Applause] [Music] you
Info
Channel: IAmTimCorey
Views: 63,964
Rating: 4.909194 out of 5
Keywords: .net, C#, Visual Studio, code, programming, tutorial, training, how to, tim corey, C# training, C# tutorial, C# app start to finish, .net core, c# 9.0, c# 9 new features, c# 9.0 new features, c# 9 features, c# 9 records, c# 9 pattern matching, c# 9 top level programs, c# 9 init only properties, .net 5.0, .net 5 features, .net 5 new features, c# 9, .net 5, whats new in c# 9
Id: f0YeVirKPfw
Channel Id: undefined
Length: 70min 59sec (4259 seconds)
Published: Wed Nov 18 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.