"Conversion from type 'DBNull' to type 'Boolean' is not valid", after checking that it's not DBNull
Asked Answered
M

1

6

In my ASP.Net Web-Application, I'm getting this error:

Conversion from type 'DBNull' to type 'Boolean' is not valid.

From this function:

Namespace atc
    Public Class Nil
        '...
        Public Shared Function Bool(ByVal Item As Object) As Boolean
            Return IIf(Item IsNot Nothing AndAlso Not IsDBNull(Item), CBool(Item), False)
        End Function
        '...
    End Class
End Namespace

As you can see, I'm explicitly checking if Item is DBNull, and if it is then I return False.

The error does not occur when Item is not DBNull, so I don't understand why this is happening.

Mahayana answered 18/1, 2012 at 16:13 Comment(0)
M
13

When using IIf then all arguments get evaluated, no matter if the condition evaluates to true or false. In your case the function will return false if Item is null or DBNull, but CBool(Item) will be silently executed in the background anyway and therefore throws an exception.

In VB.NET 2008 the If keyword was added to provide a real ternary operator. Replace your IIf function call with the following:

Public Shared Function Bool(ByVal Item As Object) As Boolean
    Return If(Item IsNot Nothing AndAlso Not IsDBNull(Item), CBool(Item), False)
End Function

Excerpt from MSDN:

An IIf function always evaluates all three of its arguments, whereas an If operator that has three arguments evaluates only two of them.

Malnutrition answered 18/1, 2012 at 16:17 Comment(2)
Wow, iff was really bad.Felucca
Although it appears to me that If has similar problems :(Felucca

© 2022 - 2024 — McMap. All rights reserved.