Disabling Null Checking
Before C# 9 (before 2020), reference types like
string could store a null value, and there was no clear way to indicate whether null was an expected option or not.
That is, you see a variable whose type is
string and you can’t simply know if you should do a null check when using and/or assigning values to the variable.
C# 9 introduced the concept of being able to indicate whether null was expected to be a valid option for any given usage. For example, in C# 9, you could configure the project to indicate that the following variable may be null:
string? text = MaybeRealStringMaybeNull();
Meanwhile, this then turns into, “Null is not expected to be a legitimate value here”:
string text = DefinitelyARealString();
In the first case, you should do a null check before using the contents of the variable. In the second one, you should do a null check when assigning it any value that might possibly be null.
By turning this feature on, the compiler will help you check for null at the right times, which can save you from all sorts of null reference exceptions that would otherwise crash your program.
This feature was available but off by default in C# 9 (see nullable-reference-types.md for how to enable this in C# 9 projects).
In C# 10 and Visual Studio 2022, new projects are created with this feature turned on. I strongly recommend leaving it on. It is a great feature, and a huge time saver, allowing you to notice null reference bugs as you type the code instead of months later when it is running in production with real users.
Still, you may find yourself wanting to turn it off. This is not hard to do.
In Visual Studio, right-click on your project in the Solution Explorer and go to Properties. This will open up the project’s properties, so you can edit them. Under Build > General, scroll down to find the property labeled Nullable and change it from Enable to Disable, and the compiler will stop giving you warnings, putting you back into a pre-C# 9 state.
If you’re not using Visual Studio, it is also very easy to just open the .csproj file in a text editor:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net6.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> </Project>
Find the line containing
<Nullable>enable</Nullable> and either change it to be
disable or remove it entirely, and you’ll achieve the same effect.