if condition with nullable

前端 未结 10 1074
抹茶落季
抹茶落季 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:06

    Anything between the parentheses from the if-statement must evaluate to true or false. A nullable bool can evaluate to null, true or false.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-02 11:13

    It's not that obvious that null should mean false. A null value means that the value is unknown or uninitialized. It's unknown whether the value is true or false. Who said null should behave like false?

    A more obvious usage for Nullable<bool> is to store something that can be either true or false, but sometimes is irrelevant or unknown, in which case the value is null.

    0 讨论(0)
  • 2021-01-02 11:15

    Simply put, it fails to compile because the specification says it should - an if condition requires a boolean-expression - and an expression of type Nullable<bool> isn't a boolean-expression:

    A boolean-expression is an expression that yields a result of type bool; either directly or through application of operator true in certain contexts as specified in the following.

    However, it's easy to work round:

    if (x.GetValueOrDefault())
    {
    }
    

    Or to possibly be clearer:

    if (x ?? false)
    {
    }
    

    The latter approach is useful as it means you can easily change the behaviour if x is null, just by changing it to x ?? true.

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