Null-conditional operator and !=

陌路散爱 提交于 2019-12-30 02:45:10

问题


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

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

If I rewrite it this way,

if (instance?.Val != 0)  

it will be evaluated to true if instance is a null reference; It behaves like

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

So what is the right way to rewrite the evaluation using this new syntax?

Edit:

instance is a field of a big object which is deserialized from JSON. There are quite a few pieces of code like this, first check if the field is in the JSON, if it is, check if the Val property does NOT equal to a constant, only both conditions are true, do some operation.

The code itself can be refactored to make the logical flow more "making sense" as indicated by Peter in his comment, though in this question I am interested in how to use null-conditional operators with !=.


回答1:


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).




回答2:


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.




回答3:


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

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



来源:https://stackoverflow.com/questions/44793887/null-conditional-operator-and

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!