C# Nullable
In C#, Nullable is a concept that allows a type to hold an additional value null. In other words, we can make a variable Nullable, so, it can hold additional null value. All Nullable variables are the instances of System.Nullable<T> struct.
The concept of Nullable is useful when we deal with databases that contain elements that may not be assigned a value.
C# provides two different ways to create Nullable types.
- By creating System.Nullable instance,
- By using ? operator
Note: we cannot create Nullable of reference type variable.
C# System.Nullable Example
In the following example, we are making Nullable with the help of System.Nullable namespace.
// NullableExample2.cs
Output:
Compile the program by using the following command.
csc NullableExample2.cs
Run the program by using following command.
NullableExample2.exe
C# Nullable using ? Operator Example 1
There is no significant difference between using of either System.Nullable or ? operator. We can use anyone as per our comfort.
// NullableExample.cs
Output:
10 a contains null value
C# Nullable using ? Operator Example 2
Output:
10 It contains null value