Null-conditional operator and !=

前端 未结 3 1093
温柔的废话
温柔的废话 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:11

    You could make use of null coallescing operator:

    instance?.Val ?? 0
    

    When instance is null or instance is not null but Val is, the above expression would evaluate to 0. Otherwise the value of Val would be returned.

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

    0 讨论(0)
  • 2020-12-31 02:28
    if ((instance?.Val).GetValueOrDefault() != 0)  
    

    the ? conditional operator will automatically treat the .Val property as a Nullable.

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