C# | Nullable types
In C#, the compiler does not allow you to assign a null value to a variable. So, C# 2.0 provides a special feature to assign a null value to a variable that is known as the Nullable type. The Nullable type allows you to assign a null value to a variable. Nullable types introduced in C#2.0 can only work with Value Type, not with Reference Type.
The nullable types for Reference Type is introduced later in C# 8.0 in 2019 so that we can explicitly define if a reference type can or can not hold a null value. This helped us to tackle the issue of NullReferenceException without using conditionals. In this article, the discussion revolves around the nullable types for value types.
The Nullable type is an instance of System.Nullable<T> struct. Here T is a type which contains non-nullable value types like integer type, floating-point type, a boolean type, etc. For example, in nullable of integer type you can store values from -2147483648 to 2147483647, or null value.
Nullable<data_type> variable_name = null;
Or you can also use a shortcut which includes ? operator with the data type.
datatype? variable_name = null;
// this will give compile time error int j = null; // Valid declaration Nullable<int> j = null; // Valid declaration int? j = null;
How to access the value of Nullable type variables?
You cannot directly access the value of the Nullable type. You have to use GetValueOrDefault() method to get an original assigned value if it is not null. You will get the default value if it is null. The default value for null will be zero.
0 0 47 457
Characteristics of Nullable types
- With the help of nullable type you can assign a null value to a variable without creating nullable type based on the reference type.
- In Nullable types, you can also assign values to nullable type. As shown in the below example.
- You can use Nullable.HasValue and Nullable.Value to check the value. If the object assigned with a value, then it will return “True” and if the object is assigned to null, then it will return “False”. If the object is not assigned with any value then it will give compile-time error.
- You can also use == and ! operators with nullable type.
- You can also use GetValueOrDefault(T) method to get the assigned value or the provided default value, if the value of nullable type is null.
- You can also use null-coalescing operator(??) to assign a value to the underlying type originate from the value of the nullable type.
- Nullable types do not support nested Nullable types.
- Nullable types do not support var type. If you use Nullable with var, then the compiler will give you a compile-time error.
Advantage of Nullable Types:
- The main use of nullable type is in database applications. Suppose, in a table a column required null values, then you can use nullable type to enter null values.
- Nullable type is also useful to represent undefined value.
- You can also use Nullable type instead of a reference type to store a null value.