C# Nullable reference types – No more null reference exceptions!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
are you tired of null reference exceptions and unexpected crashes due to uninitialized variables there's a very handy feature in c-sharp called nullable reference types this will help you catch this before it becomes a problem welcome to this video my name is phillip ekberg and today we'll be looking at nullable reference types in c sharp i believe that most of us have probably had applications crashing due to null reference exceptions if not it's really just a matter of time before it happens to you a null reference exception often occurs when you try to access properties or call a method on what you believe is an instantiated object to allocate a new instance of a reference type in csharp you use the keyword new this will make sure that your reference type has been properly allocated and stored in memory as a little side note did you know that in c-sharp 9 it becomes a little bit easier to create an instance of an object with this new language feature you don't have to explicitly declare what type you want to create an instance for if the compiler can figure it out for you that is anyways back to talking about references and reference types if you declare that you want a variable of a reference type but don't initialize it before you try to use it you will get a compiler error however consider that you are calling a method that returns a list of people it might in fact return null returning null means that it doesn't really point to any memory thus when you try to access properties or call methods there's nowhere to go and you'll have a null reference exception because the reference is null let's introduce an example we have a method here for taking attendance of people in the classroom if there's no one attending the lecture not only will i be crying but will also get a null as a result this could be considered bad application design as it would be much more appropriate to return an empty list although this is pretty common so we'll proceed with this implementation i guess in a perfect world we wouldn't have to worry about nulls which would ultimately get rid of all the null reference exceptions although if you simply replace all the nulls in your application with an arbitrary default value you might still end up having unexpected behaviors across your entire application we've now got the attendance for people in the classroom we're storing this in a local variable that we call people consider that we want to print a nice summary of all the people that are attending our class we're going to do this in a new method because we want to keep the code clean we'll expect a list of people being passed into this method and we start iterating through each item in the list and print the name of each attendee i'm sure this looks very similar to your code and by code and it's really nothing wrong with it the only problem here is that when we run the application it will in fact get a null reference exception and crash i don't really want to downplay this problem it's in fact a pretty big issue and we should probably get to fixing it the most common approach to solve these problems is to introduce null checks everywhere in the application in this very basic application finding those places is easy in larger more complex scenarios and applications it might be a little bit trickier to help us find these potential problems i'd like to introduce a language feature that was introduced in c sharp 8 which is known as the nullable reference types null reference types is really what this entire video is about it will enable you to quicker find the potential null reference exceptions i'd like to explain nullable reference types like a nullable value type you know you can just append a question mark to an int double or any other value type this would mean that this value type could now be null nullable reference types allow for sort of the same thing but with reference types and the fact that when enabled the reference types will all be non-nullable by default to enable this language feature we have a few different options we can enable it for the entire project by opening the cs prod file or we can navigate the menus inside visual studio we then set nullable to enable this will now change the way the compiler looks at the reference types they are now going to be assumed to be none null by default this here is a drastic change and means that the compiler will now warn you every time it detects something that's null or a potential null reference exception currently the only issue that the compiler finds is with the null value we return from attendance to fix this issue we have two options either we make sure that we don't return null hence we create an instance although that might change what the consumer of this method expects it to return if we simply change it to return an empty list other things in the application might break and to be honest this isn't where the null is the problem to get rid of this warning we can instead indicate that the method may return a null value we do this the same way that we indicate that a value type like an integer can be null we add the question mark changing the signature of the methods to nullable list of person means that we may get a null or an instance of a list it does not indicate that each element in the list can be null if we'd like to indicate that the list can be null as well as each element in the list could be null we'd have to change the signature to nullable list of nullable person i don't see the point in having null elements in the list though so let's not do that we can keep it simple for now and simply say that we have a result that is either null or an instance of a list this now shows a warning at another place in the application i just want to point out these are just warnings and not errors we could turn on a setting to treat warnings as errors if that's something we like now the first warning we see here is that we are assigning a nullable list of person to a non-nullable list of person to fix this warning we could change the variable type to a nullable list or a little bit of a simpler approach would be to use the var keyword this will automatically have the compiler figure out what type is returned now we're left with just one warning and i don't really want to call the method who is here if the result from the attendance call is null therefore i'm going to add a nullcheck and i'm going to print something to the console if there's no one attending my class if it's not null we are going to proceed to call the method with the list of people notice how the warning is no longer there it's because the compiler knows that we've performed a null check on the variable that we're using this here won't always be perfect and we do have ways to trick the compiler into thinking that we know better we'll get to that in just a little bit alright we've fixed a few warnings but we're still gonna get a null reference exception if we check the code for the person class it has a reference that is not initialized we might want to be able to create an instance of a person to track attendance without having to ask the person for their personal details i'm therefore going to allow this reference type to be null which will remove the warning from the person class with that changed did we get a warning somewhere else let's have a look at the code where we consume the personal details you might have guessed this but we have a warning in the who is here method this warning is telling us that calling person dot details dot first name is a potential null reference exception about to happen remember that i said previously that we can tell the compiler that we know better we can use the dammit operator which is not the actual name for it it's actually called null forgiving operator this operator is a simple exclamation mark to say that we know that this definitely won't be null indicating that the compiler is wrong here's another example consider this non-nullable reference type we set it to null which provides a warning then we're going to use the null forgiving operator to ensure the compiler that the value won't be null do you see the problem here sure the compiler is no longer providing us with a warning but we can clearly see that this here is going to be an issue guess what the compiler is for the most of the time better at understanding the code than we are a better approach in this case here would be to use the null conditional operator this means that if details is null it won't proceed to get the first name and we could use the null equalizing operator to print a default value let's also have a quick look at the details class this here is wording us that first name and last name are not initialized since these are both non-nullable by default this is why we are seeing this warning to get rid of this warning we could introduce a constructor and require first name and last name to be initialized when we create an instance while this here got rid of the warning i don't particularly like this approach mainly because it will now change the contract for how to consume the details class this might break a whole lot of usages elsewhere in the solution instead we'll make sure that we allow first name and last name to be null therefore whenever they're accessed and there's a potential null reference exception the compiler will most certainly provide a warning and to do this we'll just mark the strings as nullable strings as a final improvement to the details class i'd like to make sure that first name and last name can only be set when we create an instance however i don't want to introduce the constructor and then force them to be set when we create the instance so how would we do this this is where another new language feature from c-sharp 9 becomes really handy we can add something called the init only setters this simply allows for the set keyword to be replaced by a new keyword called init you're probably wondering why we'd want to do this this makes sure that the properties are read only but can still be set when we use an object initializer so let's add a person that's attending our lecture we can indicate that we want a person with a detailed property set to a new instance of its required type look at how beautiful this is when we're using this new expression from c sharp nine you can see that we can set the first name and last name properties in the object initializer if we try to change them afterwards we get a compiler error this is because it's only allowed to be initialized once after that it's going to be read only since the method returns an innumerable we can use the yield keyword to return a new instance without having to create a list of people this here is a handy little trick i'll add another person attending the lecture just to show you how easy this is yield is such a forgotten language feature understanding that properly is a topic for another video if that's something that you'd like to see please do leave a comment below and i'll see if i can get to that later on as we run the application it will now show everyone that's attending the lecture as a side note the details and the person class are both great opportunities to use a record if you want to learn more about how to use records and how they work i suggest that you check out the video on this channel covering that language feature with all these changes made to the application we've now successfully gotten rid of potential null reference exceptions with very minimum efforts we introduced a language feature that allows for early detection of possible problems this is a truly great addition to programming in c-sharp obviously we can't get rid of nulls completely but this is a very good step in the right direction what do you think if they recreated c sharp from scratch today do you think that they'd add nulls to the language someone once said that nulls and null reference exceptions have costed the world millions and millions of dollars if you already have a big solution where you want to use this feature you may not want to enable this for the entire project it can be a little bit overwhelming especially if you suddenly end up getting thousands of warnings of course they're warnings and you should probably attend to them but to make the process a little bit easier you can use directives to turn on or off the feature for classes and methods if you disable nullable reference types for a portion of the code where you've already started using the feature it will provide you with a warning and tell you that you're using a language feature in a context where it's not allowed you can also enable nullable reference types for portions of the code if it was not enabled for the entire project let's summarize what we've discovered in this video you can enable nullable reference types on the project level or directly in your code to quicker find potential null reference exceptions the compiler will provide you with warnings and tell you if there is a potential null reference exception it's not going to catch every case but it is going to catch a lot reference types are now non-nullable by default create a nullable reference type by using the question mark this will allow your variables to be assigned a null value you can use the null forgiving operator when you know better than the compiler this indicates that we are certain that the value won't be null you can use the null conditional and null equalizing operators to better handle potential null references the compiler will understand if you have null checks in place and won't warn you if it's obvious that the values you're using won't be null this my friends is how to use nullable reference types in c-sharp i'd love to hear in the comments if you are going to use this feature or if you find it completely useless personally i find this feature extremely useful if you liked this video please do 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 looking at nullable reference types in c sharp you
Info
Channel: Filip Ekberg
Views: 7,992
Rating: 4.9313726 out of 5
Keywords: csharp, .NET, C#, programming, C# 9.0, csharp 9, C# 9, dotnet, Filip Ekberg
Id: NDweaZZZcbc
Channel Id: undefined
Length: 18min 6sec (1086 seconds)
Published: Thu Oct 15 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.