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);
Hi Richard,
ReplyDeleteYou can also do this:
int result = myInt ?? 123;
Yep, you can definitely do that in C# (I should have mentioned it as well - doh!). I don't think it'll work in VB.NET though :-)
ReplyDelete