Sep 12, 2007

Checking Nullable Types for a Value

When people are first using Nullable types you'll often see code like the following:

int? myInt;
int result;
if (myInt.HasValue)
result = myInt.Value;
else
result = 0;
While this code is perfectly workable, it's a bit on the verbose side of things.

You can easily refactor this code using the GetValueOrDefault() method as shown here:

int? myInt;
int result = myInt.GetValueOrDefault();
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).

For example

int result = myInt.GetValueOrDefault(123);

2 comments:

  1. Hi Richard,

    You can also do this:

    int result = myInt ?? 123;

    ReplyDelete
  2. 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