Wednesday, June 11, 2008

Nullable Types - and their methods.

The Nullable type allows us to hold Value types which are not allowed to hold nulls(as reference types are) to be able to have the state of NULL.

You declare a nullable like this:
Dim intNullable As Nullable(Of Integer)

Now this Integer type can be Null -- this is handy for several reasons such as if one were reading in values from a database where the particular integer column MAY hold a null value.
However, the confusion with this object comes when the poor unsuspecting sap tries to test the value of this variable.

The most obvious method .Value (intNullable.Value) will give you the value UNLESS it is currently NULL and then it will throw an InvalidOperationException!

OK, so what we have to do is call the .HasValue method first. This returns true or false based upon value or NULL.

So you COULD call .HasValue and then if True call the .Value.

HOWEVER, their is another method called .GetValueOrDefault. This method combines both .HasValue and .Value. This handy method will give you a '0' if the value is Null or the value of the variable.

Which begs the question in my mind... WHY EVEN HAVE THE FIRST TWO METHODS?
**I'm sure there is an explanation and would love to hear it if you know.

Anyway -- that's the Nullable nugget of the day.

No comments: