Null-conditional operator and !=

前端 未结 3 1092
温柔的废话
温柔的废话 2020-12-31 01:39

With the introduction of Null-Conditional Operators in C#, for the following evaluation,

if (instance != null && instance.Val != 0)

3条回答
  •  醉梦人生
    2020-12-31 02:16

    With Null-Conditional operator returned value can always be null

    if ((instance?.Val ?? 0) != 0)
    

    If instance was null, then instance?.Val will also be null (probably int? in your case). So you should always check for nulls before comparing with anything:

    if ((instance?.Val ?? 0) != 0)
    

    This means: If instance?.Val is null (because instance is null) then return 0. Otherwise return instance.Val. Next compare this value with 0 (is not equal to).

提交回复
热议问题