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. //Below line will throw System.InvalidOperationException
  4. //Error Message: Nullable object must have a value.
  5. Console.WriteLine(num1.Value);
  6. //HasValue
  7. if (!num1.HasValue)
  8. {
  9. Console.WriteLine("num1 contains the Null value");
  10. }
  11. else
  12. {
  13. //Access Value
  14. Console.WriteLine(num1.Value);
  15. }
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;