tags:

views:

64

answers:

1

I am trying to write a generic function that will check each database parameter to see if it is null, and if so, return DBNull; if not, return the object.

So here is my function:

Public Shared Function CheckForNull(ByVal obj As Object) As Object
    If obj <> Nothing Then Return obj Else Return DBNull.Value
End Function

My problem is that some of the objects I am passing to the function are Nullable. So I may pass the function a Long? or Int?, but when a nullable type is passed to the function, it is converted to its value type. So if I pass a Long? that has a value of 0, the function returns DBNull because the Long? is converted to Long and a value of 0 for a Long is equivalent to Nothing. Is there anyway to make this function work for Nullable types as well?

If not, I will just fall back to using the following statements instead of one generic funciton call:

IIf(nullableVar.HasValue, nullableVar, DBNull.Value))

and

IIf(nonNullableVar IsNot Nothing , nonNullableVar, DBNull.Value))
+2  A: 

That is not why your logic is failing. When evaluating an expression like (x=y) or (x<>y), if either argument is Nothing, VB.Net returns FALSE. Your conditional is always falling through to the ELSE clause. So instead of:

if obj <> Nothing then

try this instead:

if obj isnot nothing then
Bill
Thanks for your response. As a C# developer having to write VB.NET, I am still struggling with the proper handling of 'Nothing'.Changing '<>' to 'IsNot' fixes the problem. However, I have a problem with the answer in that, my original evaluation 'obj <> Nothing' works for all cases except when comparing a nullable value type that has a value of zero against nothing. When I pass a string to the function that is not nothing, the function correctly returns the string.
Zach Green
Is it that the '<>' operator converts a nullable value type back to just a normal value type, and that is why when the value type has a value of 0 the comparison fails and returns DBNull?
Zach Green
There is probably some implicit conversion going on. M$ loves do "help" us wimpy VB programmers. I always put Option Strict On as the first line of any code file to prevent this sort of unexpected behavior.
Bill
Thanks. Didn't know about 'Option Strict On' (just took on an old VB.NET project; I'm still trying to get my head around the differences between C# and VB.NET). Turned it on for the project; 3 hours and about 1000 errors later...No more implicit conversions, and hopefully no more unexpected behavior.
Zach Green