if condition with nullable

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

    Technically it doesn't work because Nullable does not define a conversion operator to bool.

    Practically it is not supported for a variety of reasons, including:

    • There are no implicit conversions to bool anywhere in C# -- why should there be in Nullable?
    • Any conversion available would have to be declared for every T in Nullable -- how is that possible when you can plug in your own type as T that the compiler knows nothing about?
    • What would be the semantics of if(!x)?

提交回复
热议问题