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:
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.
When variable's HasValue property is True, then you should use Value property to access the value of the variable.
Source Code:
- //Nullable Declaration
- int? num1 = null;
- //Below line will throw System.InvalidOperationException
- //Error Message: Nullable object must have a value.
- Console.WriteLine(num1.Value);
- //HasValue
- if (!num1.HasValue)
- {
- Console.WriteLine("num1 contains the Null value");
- }
- else
- {
- //Access Value
- 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.
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;
Nullable<Nullable<string>> str1;

Michael GriffithsPosted Apr 8, 2016, 4:06 AM
Nice