VB.NET Nullable Types Gotcha

Nullable types ― A valuable language addition in .NET allowing value types to store null values. It helps a variable get it's default value which is not part of the business logic. A very common example is integer type whose default value is always set to 0 restricting programs using 0 as a legitimate value. However, Nullable types take away this restriction by allowing null values to be set for value types like reference types.
While using nullables we need to be very careful specially when programming in VB.NET where implicit casting is frequently used. Consider the example below:



ByVal temp As Nullable(Of Integer)
temp = Request.QueryString("DataBridgeQueueID")


Guess what value "temp" will get if there is no "DataBridgeQueueID" passed in the query string?? a nurd like me will expect Nothing in "temp" which is wrong. The reason being that QueryString always returns string and in my case null (Nothing) string which is equal to 0 when assigned to an integer. Although I have declared "temp" variable as nullable, it will continue to have 0 because of implicit type casting. So what to do then?? You are right, just do a CType and life is easy.

'If Option Strict On
temp = CType(CType(Request.QueryString("DataBridgeQueueID"), Object), Nullable(Of Integer))

'If Option Strict Off
temp = CType(Request.QueryString("DataBridgeQueueID"), Object)



HTH,

0 comments:

Post a Comment