How does GetValueOrDefault work?
A NullReferenceException
isn't thrown, because there is no reference. The GetValueOrDefault
is a method in the Nullable<T>
structure, so what you use it on is a value type, not a reference type.
The GetValueOrDefault(T)
method is simply implemented like this:
public T GetValueOrDefault(T defaultValue) {
return HasValue ? value : defaultValue;
}
So, to replicate the behaviour you just have to check the HasValue
property to see what value to use.
GetValueOrDefault ()
prevents errors that may occur because of null. Returns 0 if the incoming data is null.
int ageValue = age.GetValueOrDefault(); // if age==null
The value of ageValue
will be zero.
thing
isn't null
. Since structs can't be null
, so Nullable<int>
can't be null
.
The thing is... it is just compiler magic. You think it is null
. In fact, the HasValue
is just set to false
.
If you call GetValueOrDefault
it checks if HasValue
is true
or false
:
public T GetValueOrDefault(T defaultValue)
{
return HasValue ? value : defaultValue;
}