Why is there a difference in checking null against a value in VB.NET and C#?

前端 未结 7 1721
被撕碎了的回忆
被撕碎了的回忆 2020-11-29 19:02

In VB.NET this happens:

Dim x As System.Nullable(Of Decimal) = Nothing
Dim y As System.Nullable(Of Decimal) = Nothing
         


        
7条回答
  •  被撕碎了的回忆
    2020-11-29 19:31

    Because x <> y returns Nothing instead of true. It is simply not defined since x is not defined. (similar to SQL null).

    Note: VB.NET Nothing <> C# null.

    You also have to compare the value of a Nullable(Of Decimal) only if it has a value.

    So the VB.NET above compares similar to this(which looks less incorrect):

    If x.HasValue AndAlso y.HasValue AndAlso x <> y Then
        Console.WriteLine("true")
    Else
        Console.WriteLine("false")  
    End If
    

    The VB.NET language specification:

    7.1.1 Nullable Value Types ... A nullable value type can contain the same values as the non-nullable version of the type as well as the null value. Thus, for a nullable value type, assigning Nothing to a variable of the type sets the value of the variable to the null value, not the zero value of the value type.

    For example:

    Dim x As Integer = Nothing
    Dim y As Integer? = Nothing
    
    Console.WriteLine(x) ' Prints zero '
    Console.WriteLine(y) ' Prints nothing (because the value of y is the null value) '
    

提交回复
热议问题