tags:

views:

141

answers:

4

I need to make something like :

if isdbnull(value) or value = something then
'do something
else
'do something else
end if

of course i get an error using this method , so my question is how do i rewrite it to avoid the "operator not defined for dbnull and something" error ?

A: 
value Is DBNull.Value
ZippyV
i still get Operator '=' is not defined for type 'DBNull' and string "something".
Iulian
A: 

value is nothing

Jim
no, the problem is in the "or value = something " part, that's what is causing the exception
Iulian
+2  A: 

There are a few approaches to this, and which you use may depend on the values you're working with. However, if you want something that catches all conditions then I'd do this:

If Value Is Nothing OrElse IsDbNull(value) Then
  'do something
Else
  'do something else
End If

This will check if the Value is nothing, which can sometimes happen without the value actually being DBNull.

But the most important part of this is the OrElse. OrElse is the short-circuiting operator which terminates the evaluation of the condition as soon as the runtime knows what the outcome will be. By contrast, the Or operator will execute the entire condition no matter what, and that is the reason your original code fails.

EDIT:

Now that I look at your example code again, I can see how my NotNull() function may help you:

Public Shared Function NotNull(Of T)(ByVal Value As T, ByVal DefaultValue As T) As T
 If Value Is Nothing OrElse IsDBNull(Value) Then
  Return DefaultValue
 Else
  Return Value
 End If
End Function

Usage:

if NotNull(value, something) = something then
'do something
else
'do something else
end if
Steve Wortham
I'm hot sure this is exactly what the question is asking for, but the key is the "OrElse" part for sure.
Jimmy
This is it! OrElse did it , thanks a lot !
Iulian
Sure, no problem. Actually now that I look at your original code again, I can see how my NotNull function may help you.
Steve Wortham
yes, it's a very clever solution that NotNull function, thanks again
Iulian
Jimmy, I think you're right. I had to look at it again to understand the intention of the example code, but my latest "edit" addresses that.
Steve Wortham
+2  A: 

I tend to use the OrElse, AndAlso operators

If IsDBnull(value) OrElse value = something Then
    ''#do something
Else
    ''#do something else
End If

The shortcuts operator means the rest of the If conditions won't be executed if the first is true.

Edit: Steve beat me to it while I was formatting my answer :)

Cylindric
:) you still get a vote up for trying , thanks
Iulian
Heh, thanks :) Formatting will be the death of me...
Cylindric