Tim on November 12th, 2007

In the first part of my series on Generics in VB.NET I discussed the advantages of generic collections. In this installment I’ll cover the Nullable Generic Structure.

First, let’s cover some background. A type is nullable if it can be assigned a value or Nothing (null in C#). For example a String object is nullable because it can be assigned either a value or Nothing. On the other hand, value types are not nullable. An Integer cannot be assigned Nothing. To put it simply, reference types are nullable. Value types are not.

Now that we’re experts at nullable and value types in .NET, let’s cover the usefulness of the nullable generic structure. At times it’s useful to know if a value has been assigned to a variable that you cannot initialize as Nothing, but you don’t want to initialize it with the default value. Using the nullable structure can help simplify your code in certain instances. Let’s take a look at two examples.

Without using the nullable structure:

Dim value1 As Integer

‘do some work

If value1 = 0 Then
      ‘the value wasn’t changed, but we can’t be completely sure it wasn’t actually set to 0
      ‘because an Integer is initialized to 0
Else
      ‘we’re sure the value was changed, so we’ll continue processing
End If

Now using the nullable structure:

Dim value1 As Nullable(Of Integer)

‘do some work

If Not value1.HasValue Then
     ‘because the variable doesn’t have a value,
     ‘we’re sure the value hasn’t been set
Else
     ‘we’re sure the value was changed, so we’ll continue processing
End If

Now of course these examples are contrived, but I think they prove the point. If you want to check if a value type has been assigned a value, consider using the nullable generic structure. It will give you an easy way to “assign” and test for null in a value type.

Leave a Reply

You will be able to edit your comment after submitting.