Handling Null Values (Part Two)
August 11th, 2008During my studies whilst over in Baku for work, I came onto the topic of Generics in .Net. I wont bore you with all the details of Generics here, but one of the interesting features of it, is that if you assign a generic variable a value of nothing when the generic is something like a date, or an integer, you get a default value for that type.
This got me thinking about whether I could compress the whole class from my previous Blog into just a single generic Function. I believe I can! See the code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | Public Class HandleNullValues Private Sub New() 'Does nothing. Set to private to prevent instantiation of the class. End Sub Public Shared Function CheckNull(Of T)(ByVal obj As Object) As T If IsDBNull(obj) Then Dim ret As T = Nothing Return ret Else Return CType(obj, T) End If End Function Public Function DefaultValue(Of T)() As T Dim ret As T = Nothing Return ret End Function End Class |
As you can see, this class consists of just two methods (ignoring the ‘new’ method). The core of the class is the CheckNull Function. This will compare the object and return the objects value if there is one. If it is null, it returns nothing (for objects) or the default value of the type (for things like dates/integers/boolean/etc).
There is a proviso to this function, however. The usage is not necessarily the most clear cut. You need to use the syntax below:
Dim myVal as Integer Dim obj as new object myVal = CheckNull(of Integer)(obj)
As you can see, you need to specify the generic type in brackets after the Function name, but before the parameters list.
The second Function, DefaultValue, takes no parameters (although you still need to specify the generic type as above). This Function will return the default value of the given type. I’ve only really provided it so that you can see what will be returned if the object is null. Remember that, this may or may not be the same as a valid object value (ie, if the object holds an integer value of 0, then this is the same as a null object)