3

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 ?

4 Answers 4

6

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
Sign up to request clarification or add additional context in comments.

4 Comments

I'm hot sure this is exactly what the question is asking for, but the key is the "OrElse" part for sure.
Sure, no problem. Actually now that I look at your original code again, I can see how my NotNull function may help you.
yes, it's a very clever solution that NotNull function, thanks again
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.
3

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 :)

Comments

0
value Is DBNull.Value

1 Comment

i still get Operator '=' is not defined for type 'DBNull' and string "something".
-1

value is nothing

1 Comment

no, the problem is in the "or value = something " part, that's what is causing the exception

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.