if condition with nullable

前端 未结 10 1119
抹茶落季
抹茶落季 2021-01-02 10:20

There is a lot of syntax sugar with Nullable like those:

int? parsed to Nullable

int? x = null
   if (x != null) // Parsed          


        
10条回答
  •  [愿得一人]
    2021-01-02 11:10

    I think that wouldn't be a good idea. That null evaluates to false doesn't feel natural. Especially in if+else statements. So forcing the user to be explicit with: if(nb==true) and if(nb==false) is a good idea IMO.

    MSDN says:

    bool? b = null;
    if (b) // Error CS0266.
    {
    }
    

    This is not allowed because it is unclear what null means in the context of a conditional. To use a bool? in a conditional statement, first check its HasValue property to ensure that its value is not null, and then cast it to bool. For more information, see bool. If you perform the cast on a bool? with a value of null, a InvalidOperationException will be thrown in the conditional test.

    http://msdn.microsoft.com/en-us/library/bb384091.aspx

    Some of the answers to my question Why are there no lifted short-circuiting operators on `bool?`? touch on these aspects too

提交回复
热议问题