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:
- 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:
-
- int? num1 = null;
-
-
-
- Console.WriteLine(num1.Value);
-
-
- if (!num1.HasValue)
- {
- Console.WriteLine("num1 contains the Null value");
- }
- else
- {
-
- Console.WriteLine(num1.Value);
- }
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;