Comparing nullable (of boolean)

I am trying to compare two type variables nullable(of boolean)in VB.NET 2010. One of the variables is False and the other is Nothing. Now I expected the following expression to evaluate to true, but it is not:

Dim var1 as nullable(of boolean) = False
Dim var2 as nullable(of boolean)
var2 = Nothing

If var1 <> var2 Then
 msgbox "they are different"
End If

Why can't I see my MsgBox? How to compare two NULL (boolean) values?

+5
source share
4 answers

Nullable.Equals Indicates whether the two specified Nullable (Of T) objects are equal.

    If Not Nullable.Equals(var1, var2) Then
        MsgBox("they are different")
    End If
+19
source

This is due to the fact that in VB.NET

Console.WriteLine(False = Nothing)

displays True.

This has nothing to do with the error.

+2
source

, .

Function compareNullableBooleans(ByVal firstBool As Nullable(Of Boolean), _
                                 ByVal secondBool As Nullable(Of Boolean))
    If firstBool.HasValue And secondBool.HasValue Then
        Return (firstBool = secondBool)
    ElseIf firstBool.HasValue And secondBool.HasValue = False Then
        Return False
    ElseIf firstBool.HasValue = False And secondBool.HasValue = True Then
        Return False
    Else
        Return True
    End If
End Function

, , , : p

+2

, Value HasValue. http://msdn.microsoft.com/en-US/library/19twx9w9(v=VS.80).aspx

:

If (var1.HasValue And var2.HasValue) And (var1.Value <> var2.Value) Then
      '
End If

It has been quite a while since I wrote VB. I am usually a guy from C #. However, this concept is correct.

0
source

All Articles