|
In this article we will see how to assign value of System.Nullable<T> to T. System.Nullable<T> is used when underlying types is a value type that can also be assigned null like a reference type.
When we try to assign System.Nullable<T> to T like below
System.Nullable<Double> nDbl; nDbl = 5.6; Double dbl = nDbl;
compiler throws below error.
Cannot implicitly convert type 'double?' to 'double'. An explicit conversion exists (are you missing a cast?)
System.Nullable<T> provides GetValueOrDefault to get value of System.Nullable<T> object.
System. Nullable<Double> nDbl; nDbl = null; Double dbl = nDbl.GetValueOrDefault();
If nDbl is null GetValueOrDefault returns 0.
System. Nullable<Double> nDbl; nDbl = null; Double dbl = nDbl.Value;
If Value is used instead of GetValueOrDefault to get value from System.Nullable<T> which is assigned null, at runtime Nullable object must have a value will occur.
Use GetValueOrDefault to get value from System.Nullable<T>.
|