C# 8.0 Nullable References

Use C# 8.0 nullable references to signal a possible NullReferenceException.

To prevent a NullReferenceException, we should check and defend against null. The real question is when an object reference might be null and therefore when we should add a null check. That’s precisely what C# 8.0 solves with the nullable references feature.

So far, all references have been nullable by default. But C# 8.0 nullable references change this assumption: all reference variables are now non-nullable by default. This means that when we access the properties or methods of references that might be null, it results in compiler warnings or errors.

This is a big change. Therefore, we need to now turn this feature on at the project level in our .csproj files.

Turning on nullable references

Let’s revisit the example from a previous lesson. This time, let’s turn nullable references on.

Press + to interact
main.cs
NRE.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<!-- ^^^^^^ -->
<!-- We could use netcoreapp3.1|net5.0|net6.0 too -->
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<!-- ^^^^^^ -->
<!-- We could use enable|disable|warning too -->
<!--<WarningsAsErrors>nullable</WarningsAsErrors>-->
<!-- ^^^^^^^^ -->
<!-- We can take the extreme route -->
</PropertyGroup>
</Project>

To use nullable references, we need to target .NET Core 3.0 and upward. And, in our .csproj files, inside the <Nullable> node, we could use enable, disable, or warning. Unlike enable, which turns on all compiler checks, the warning ...