Reference types are objects that are stored on the
When an object has not been assigned to a reference type, the value is set to null
. Otherwise, the value is set to a valid address on the heap, where the object is stored.
At times, the null
value may be acceptable. However, it is often considered to be an illegal value that leads to ArgumentNullExceptions
and NullReferenceExceptions
.
C# version 8.0 allows us to pre-set properties for reference types.
Accordingly, a reference type can either be nullable or non-nullable.
As the name suggests, nullable reference types may be null
. When variables may be null
, the compiler enforces specific rules to ensure you have properly checked for a null reference.
Variables can only be dereferenced once the compiler is sure that the value is not null
. Variables can also be initialized with null
or assigned null
at any point in the code.
Non-nullable reference types cannot be null
.
When a variable cannot be null
, the compiler enforces specific rules ensuring that dereferencing these variables is safe and will not lead to an error or exception.
Variables cannot be initialized with or assigned a null
value.
Before we can work with nullable or non-nullable reference types, we must first enable the feature.
To enable the feature, you must add the following line in the project file (csproj
):
<Nullable>enable</Nullable>
Once the feature has been enabled, we can declare nullable reference types using the ?
operator.
string? str;
The above statement declares a nullable string, str
.
Once the feature is enabled, any variable declared without ?
appended to the type is considered non-nullable. This applies to all reference type variables in your existing code.
The introduction of this feature from version 8.0 allows for several benefits that are not present in earlier versions:
Allows the programmer to clearly show their intent when declaring variables.
Provides protection against null reference exceptions.
The compiler warns you if you dereference a nullable reference when it may be null.
class NullableDemo{static void Main(){int x = null; // replace with int? x = null to run codeif (x == null)System.Console.WriteLine("x is null");elseSystem.Console.WriteLine("x is" + x);}}
In the above code, we define an integer variable x
and initialize it with null
.
Upon running the code, we are dealt with an error. This is because the integer class is a value type (non-nullable) and cannot be assigned null
.
However, we want the compiler to know that x
may be null. To declare our intent to the compiler, we append ?
to the type to define the variable as nullable.
Running the code now gives us a valid output.
class NullableDemo{static void Main(){int? x = null;if (x == null)System.Console.WriteLine("x is null");elseSystem.Console.WriteLine("x is" + x);}}