if condition with nullable

前端 未结 10 1128
抹茶落季
抹茶落季 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条回答
  •  萌比男神i
    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 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.

提交回复
热议问题