Nullable Types
Nullable Modifier
- Often it is desirable to represent values that are "missing" (unknown or unassigned)
- You can declare a type to allow a null value or not, with the nullable modifier
int? number = null;
- When the programmer opts to allow a variable to be null, they takes on the additional responsibility of being sure to avoid dereferencing a variable whose value is null.
Deferencing Nullable Types
- For most part dereferencing a nullable value type that represents null will not throw a nullable exception. Members like HasValue, ToString()
- Dereferencing a null value type throws an InvalidOperationException
- Invoking GetType() when the value represents null does throw a NullReferenceException, because GetType() is not a virtual method,
Nullable Reference Types
- Prior to C# 8.0, all reference type variables allowed null. Reference type variables are nullable by default
- C# 8.0 introduced a feature known as nullable reference types.
- Reference type declarations can occur with or without a nullable modifier. In C# 8.0, declaring a variable without the nullable modifier implies it is not nullable.
- For backward compatibility, nullability is not enabled by default on existing projects. On new projects nullability is enabled at the start.
- There are several mechanisms to configure nullability: the #nullable directive, project properties, and even the command line.
Directive
#nullable enable
Project Properties
<Nullable>enable</Nullable>
Command Line
dotnet build /p:Nullable=enable