C# 8.0 just rolled out with plenty of new features. One of the most important is the support of nullable reference types (NRT). A bunch of words that don't seem to explain what it does. I mean, aren't all types (except value types) already nullable?
What Microsoft means by NRT is that now you can explicitly tell the compiler to check for null values. They do that by switching the default from null to not null for all types. So unless you explicitly specify it, you can assume that variables cannot be null anymore.
Why do that? Well it's the first attempt by Microsoft to fix the dreaded
NullReferenceException that has plagued so many applications. Many have even called the decision to allow null values in C# the billion-dollar mistake. You can also look at my other post (Why null in C# is so bad) for my take on the subject.
First of all, to try it, you must activate it. Either create a new application that runs on
.net core 3.0
or open your .csproj
and add this.<LangVersion>8.0</LangVersion>
<Nullable>Enable</Nullable>
<LangVersion>8.0</LangVersion>
is to enable the C# 8.0 features and<Nullable>Enable</Nullable>
is to switch the compiler behavior from all types null
by default to all types not null
by default.You can also enable/disable this feature only for a specific block of code using these instructions
#nullable enable
#nullable disable
#nullable restore
The compiler will then run static analysis on your code and add a compilation warning when it detects that a value can be null in a specific code path.
e.g.
// warning CS8600: Converting null literal or possible null value to non-nullable type
string a = null;
// warning CS8602: Dereference of a possibly null reference
var l = a.Length;
This feature also introduces two new operators to deal with those cases.
If we go back to the previous block of code, we now have all the tools to get rid of those warnings. (Note that in this case, those warnings are legit, and you should handle them in another way. It's just an example to demonstrate how to use those operators.)
// this will make sure we can assign a null value to that variable
string? a = null;
// this will remove the warning and let us try to call `.Length`
var l = a.Length;
NRT is a powerful tool that we'll all need to learn to use. It can bring us closer to correctness with the elimination of some runtime problems by discovering them in the earliest stages of your Software Development Life Cycle (SDLC). This practice is also known as Shift Left. The idea is to raise issues sooner in the SDLC. A problem found during development costs way less that one found in production.
All code samples are available on github
https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references
Previously published at https://blog.miguelbernard.com/c-8-0-nullable-reference-types-are-here/