开发者

comparing nullable(of boolean)

I'm trying to compare two variables of type nullable(of boolean) in VB.NET 2010. One of the variables has a value False and the other is Nothing. Now I was expecting the following expression to evaluate to true, but this is not the case:

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 don't I see my MsgBo开发者_运维问答x? How should I compare two nullables (of boolean)?


You can use Nullable.Equals:

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

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


This is because in VB.NET

Console.WriteLine(False = Nothing)

prints True.

This has nothing to do with nullability.


I believe that nullable variables have a Value and HasValue property. http://msdn.microsoft.com/en-US/library/19twx9w9(v=VS.80).aspx

Essentially you'll have to say:

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

It's been quite a while since I wrote VB. I'm typically a C# guy. The above concept is right, though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜