Nullability in C#
C# allows us to specify if a given variable/argument/… is nullable or not. It works for both value and reference types.
However, in some cases that is not enough, and we can do more. Here’s an example:
The above method would be used as follows:
GetFirstName method specifies that its output may be
It happens only when the input is null as well, but it’s not communicated
in any way to the clients, causing a warning from the compiler,
even though the result will not be
For cases like that, .NET comes with a bunch of nullability attributes that enrich nullability metadata of the method with more intricate details. We could improve the method like this:
We’ve added the
which will aid the compiler in delivering warnings only if the input to the
method is nullable. In the example shown before, the variable
fullName was no
nullable. With the attribute in place, compiler will not generate the null
reference warning anymore.
Another case where theses attributes come useful is properties with getters and setters. It could be that a setter accepts both null and non-null inputs, while the getter always returns a non-null value, because it has some default. It is illustrated below:
The AllowNull attribute specifies pre-conditions, and only applies to arguments. The get accessor has a return value, but no parameters. Therefore, the AllowNull attribute only applies to the set accessor.