Value:
This property is a read only property which retrieves the
value associated with the type.This property will throw an exception when it is
accessed with a null value.
int? mobile = null;
int mymobile = mobile.Value;
The above line will throw a exception,
“Invalid operation exception”
Nullable object should have value.
HasValue:
This property returns a Boolean indicating whether the
variable contains a value.
So the above exception can be prevented by writing the code
like,
if (mobile.HasValue)
{
int mymobile = mobile.Value;
}
Consider a situation like,
int? n1 = 2;
int n2 = 3;
Now what will be output type of (n1*n2) ?
int sum = n1 * n2;
The above operation will throw an error.
This operation gives a result which a nullable type can hold
and thus it can be assigned to a variable like,
int? sum = n1 * n2;
We can call these operators as Lifted operator’s i.e., it will
lift the non nullable type to nullable type. Assigning null to any of the above
variable will result null. The same behavior applies to + and – operators.
Getting a default value with Nullable Types:
int? n1 = null;
int n2 = 3;
(n1 ?? 10) will return the value 10.This will be useful when
we are fetching a allow null field from database and assigning to a non
nullable type or it can be used in a operation like below. Hence we can assign
a default value.
int product = (n1 ?? 10) * n2;
Now product will hold 30 since (n1 ?? 10) will return 10.
|