Thursday, August 30, 2007 12:00 AM
bart
Visual Basic 9.0 Feature Focus - Nullable types
Welcome back to the Visual Basic 9.0 Feature Focus blog series. In this post, we'll cover Nullable Types, a feature that has been available in C# since version 2.0. Nullable types help to close the gap between value types and typical database representations of these, which allow values to types not to be set. There are two big categories of types in the CLS, and thus in Visual Basic too: reference types and value types. A simple of the former one is String while numerical types like Integer are samples of value types. Reference types can point to nowhere using "Nothing", while value types should have a value from their value domain (e.g. -2^32 to 2^32 - 1). So what do you do with a Customer object that has an Age property declared as an Integer but it's possible to have a missing age? Various tricks are possible: keep an additional Boolean value to indicate whether or not the value has been set, reserve a special value to indicate a value isn't set (e.g. Age = -1), ...
However, nullable types are much easier and basically wrap value types in a generic object of type Nullable(Of T) which is a structure that can have Nothing as its "value" (with aid from the compiler in case of C# - see section 6.1.5 in the spec). In fact, you could use the Nullable(Of T) class already in VB 8.0:
Dim i As Nullable(Of Integer)
Dim b As Boolean
i = Nothing
b = i.HasValue 'Will be False
i = 123
b = i.HasValue 'Will be True
Dim j As Integer = i.Value 'j = 123
However, where VB 8.0 is different from C# 2.0 is the lack of integrated syntax to denote a nullable type: you have to write Nullable(Of ...) manually each time. In VB 9.0 this has been solved:
Dim i As Integer?
The question mark is used to make a Nullable for the specified value type:
Notice that if a value has been assigned to a nullable variable, you can just write the following to get the value back:
Dim j As Integer = i 'j = 123
There's no need to call the Value property explicitly. If you try to get the value of an unset nullable variable, you'll get an exception thrown in your face:
The use of nullables goes even further by means of three-valued logic and null propagation when working with arithmetic operations on nullable value types. Take a look at the following fragment:
Dim a As Integer? = Nothing
Dim b As Integer? = 123
Dim c As Integer? = a + b
In here c will get the 'value' Nothing. Thus, whenever you apply arithmetic operations on one or more nullables of which one is null-valued (Nothing), the result will be the null value too.
Nullable types are especially useful when mapping database schemas to objects, as is done in LINQ to SQL for example. Tomorrow, we'll look at the Ternary Operator 'If' which makes working with these Nullable Types easier in some cases.
Happy coding!
Del.icio.us |
Digg It |
Technorati |
Blinklist |
Furl |
reddit |
DotNetKicks