C#: Not-nullable reference types

As it turns out, C# has support for non-nullable reference types, that is, variables with reference types (typically object types) that may not be assigned null. The following thus is illegal:

object foo = null;

This requires a compiler switch to be set at the project level, to enable a so-called “nullable annotation context”. This tells the compiler to infer nullable state for all variables, and warn in any situations where a regular reference variable may turn null. A typical example might be a declaration without assignment, which would get null default-assigned. Of course, you can declare a variable to possibly be null just like for value types by appending ?.

It’s a pitty this is turned into a compiler flag: Now, when reading C# code, you can not really be sure if it was written with a certain nullability checking in mind. While I see the useful reason of backwards compatibility, having this enforced for everyone everywhere would clear up this possible missunderstanding. In fact, as the checks only yield warnings, not errors, this would not even be a blocker. Of course, you can convert these warnings to errors, if you are so inclined.

You can enable the setting by adding the Nullable setting to all .csproj files:


Apparently, they don’t mix well with structs and arrays; I’d recommend to stick to references and lists.

Also, parameters can receive a rather detailed set of attributes to denote behaviour wrt. nullability. For example, a method can declare that it will not return null when a specific parameter is not null as well.

Addendum 1: You can even restrict generic type parameters to be not null, and this will work for reference types as well. The constraint must be like where T : notnull.