Nullable in C# and Its Use

Introduction:
  • Dot Net have two types of data types- Value type and Reference type. Reference type variables can contain null values but Value type variable cannot be null.

  • Nullable allows value type variables to be assigned null like a reference type.

  • Nullable will add Null value to existing datatype.
Syntax:
 
System.Nullable<T> variable       -or- T? variable
T can be any value type.
 
e.g. By default Bool can have values True, False.
Bool ?isTrue will have values True, False and Null.

Dot Net provides two properties:
  • HasValue
  • Value
HasValue:
  • It is of type bool. It is set to true when the variable contains a non-null value.
  • You Can use this property to check if variable contains value or not.
Value:

When variable's HasValue property is True, then you should use Value property to access the value of the variable.

Source Code: 
  1. //Nullable Declaration  
  2. int? num1 = null;  
  3.               
  4. //Below line will throw System.InvalidOperationException  
  5. //Error Message: Nullable object must have a value.  
  6.  Console.WriteLine(num1.Value);  
  7.   
  8. //HasValue  
  9. if (!num1.HasValue)  
  10. {  
  11.            Console.WriteLine("num1 contains the Null value");  
  12. }  
  13. else  
  14. {  
  15.              //Access Value  
  16.              Console.WriteLine(num1.Value);  
  17. }  
Practical use of Nullable:
e.g. the value in database is null.

e.g. When deserializing the data from xml or json,

It becomes difficult to deal with the situation if the value type property expects a value and it is not present in the source.
Nested nullable types are not allowed.

Nullable<Nullable<string>> str1;
Next Recommended Reading Nullable Types In C#