The nullable type can represent a normal or regular set of values for its value type including the null value.
If we take an example of bool type, then Nullable<bool> can contain set of values like true or false or null.So, assigning null value to bool is useful when we are dealing with database in which the Boolean field may store value like true or false or it may be sometimes undefined.
Nullable Types are instances of System.Nullable struct.
Declaration:
A nullable type can be declared similar to normal variable but with ? modifier at the end of keyword.For example,
int? number = null;
Here ? denotes that the object is a Nullable object of that specific datatype(here it is int).
Alternative way of declaring Nullable type is,
Nullable<int> number = null;
Properties:
An instance of nullable has two public properties:
1.HasValue : This property returns true if the variable contains a value, or false if it is null. 2.Value : This property returns a value if one is assigned, otherwise it will throw an exception.(InvalidOperationException) So,to avoid this exception, the HasValue member is used to test if the variable contains some value before doing any operation with the nullable types. For example:
if(number.HasValue)
{
int num = number.Value;
}
|
Default value:
The ?? operator is used to assign a default value to a nullable type.
For example:
int n1? = null;
int n2 = 5;
int sum = (n1 ?? 3 ) + n2 ;
Note: We cannot create nullable types with reference types.
|