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

前端 未结 7 1706
被撕碎了的回忆
被撕碎了的回忆 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:38

    Look at the generated CIL (I've converted both to C#):

    C#:

    private static void Main(string[] args)
    {
        decimal? x = null;
        decimal? y = null;
        y = 5M;
        decimal? CS$0$0000 = x;
        decimal? CS$0$0001 = y;
        if ((CS$0$0000.GetValueOrDefault() != CS$0$0001.GetValueOrDefault()) ||
            (CS$0$0000.HasValue != CS$0$0001.HasValue))
        {
            Console.WriteLine("true");
        }
        else
        {
            Console.WriteLine("false");
        }
    }
    

    Visual Basic:

    [STAThread]
    public static void Main()
    {
        decimal? x = null;
        decimal? y = null;
        y = 5M;
        bool? VB$LW$t_struct$S3 = new bool?(decimal.Compare(x.GetValueOrDefault(), y.GetValueOrDefault()) != 0);
        bool? VB$LW$t_struct$S1 = (x.HasValue & y.HasValue) ? VB$LW$t_struct$S3 : null;
        if (VB$LW$t_struct$S1.GetValueOrDefault())
        {
            Console.WriteLine("true");
        }
        else
        {
            Console.WriteLine("false");
        }
    }
    

    You'll see that the comparison in Visual Basic returns Nullable<bool> (not bool, false or true!). And undefined converted to bool is false.

    Nothing compared to whatever is always Nothing, not false in Visual Basic (it is the same as in SQL).

    0 讨论(0)
提交回复
热议问题