Checking Nullable Types for a Value
When people are first using Nullable types you'll often see code like the following:
int? myInt;While this code is perfectly workable, it's a bit on the verbose side of things.
int result;
if (myInt.HasValue)
result = myInt.Value;
else
result = 0;
You can easily refactor this code using the GetValueOrDefault() method as shown here:
int? myInt;You can also specify a value in the parameters to return something other than 0 (or whatever the default value for the type normally is).
int result = myInt.GetValueOrDefault();
For example
int result = myInt.GetValueOrDefault(123);