C# and nullable value types

In C# you can declare nullable value types.  (This isn’t really what happens but the syntax looks like it.)  This is an unusual construct for those who come from other “lower-level” languages such as C++.

For example, the following declaration of “i” can not be set to null.

int i = 42;

However, in the following example, the following can be done.

int? j = 42;
int? k = null;

This blows my C++ brain.  In reality, “j” and “k” are not ints.  They are objects of type System.Nullable<T> as Microsoft describes here.

So, to safely coerce to int, you will need to check the value to be sure it is not null.  One approach is to use the HasValue method to make decisions or the GetValueOrDefault to simply get the default base type value.  For that matter, you can assign in a try-catch block but that seems so evil.

Finally, the cleanest type is the null-coalescing operator which is another foreign concept to C++ type brains.

Check out each example below.

int? i = null;
int j;

if (i.HasValue)
   j = (int) i;
else
   j = 42;

// j = 42 as i is null
Console.WriteLine("j = " + j.ToString());

// y is set to zero 
j = i.GetValueOrDefault();
// j = 0 as i is null
Console.WriteLine("j = " + j.ToString());

// an exception? really?  
try
{
    j = i.Value;
}
catch (InvalidOperationException e)
{
    Console.WriteLine("Why would anyone do this?");
}

// my favorite
j = i ?? 42;
Console.WriteLine("j = " + j.ToString());

The output you ask?  (That’s right, I heard you.)

j = 42
j = 0
Why would anyone do this?
j = 42

Using an exception is like having only one square of single-ply toilet paper.  If it is all you have, you use it.  However, we both know there are better methods.

Leave a Reply

Your email address will not be published. Required fields are marked *