Nullability

Published on Tuesday, January 02, 2024

Nullability

For official docs on Nullable Reference Types (NRTs), see Nullable Reference Types.

Man… nulls, you know? The "billion dollar mistake", yadda yadda. Microsoft introduced the ability to opt into nullable reference types in 2019, so you should probably be using it by now. If your project file doesn’t yet have...

<Nullable>enable</Nullable>

...present, you could add it, but then the whole project will light up with warnings. If you didn't want to spend the rest of your day cleaning that up, you can enable NRT on a file-by-file basis by adding...

#nullable enable

...to the top of your current code file.

Why is this a good thing? See this code:

User GetUserByName(string name)

What can it return? Before NRT, it could return either a User or null; you can’t tell from the signature. After NRT, you can assume that it will not return null. If, after NRT, you wanted a method that might return null, it has to look like this:

User? GetUserByName(string name)

Now you are not in a position of having to check for null “just in case”; things either can be null, or they can’t.

Broadly speaking, fields should only be marked as nullable (with a “?”) if you are explicitly setting it to null in code; and you shouldn't be doing that very often. One exception is default parameters in method declarations; you will have to change...

void SomeMethod(string name = null)

...to...

void SomeMethod(string? name = null)

If an instance's type is not nullable, you both don't have to and shouldn't check if it's null; it confuses the linter. Similarly, specifying “.Value” for nullable variables that you have already checked for nullability will confuse the linter; try removing the “.Value”.

Implicitly typed variables (var x) are assumed to be nullable:

var strings = new List<string>();

The type of “strings” is “List<string>?”.

This is not usually a problem, but if it becomes one, initialize the variable so:

List<string> strings = new();