Null-conditional operator and !=

2019-02-08 11:58发布

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 !=.

3条回答
我命由我不由天
2楼-- · 2019-02-08 12:30

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

查看更多
贪生不怕死
3楼-- · 2019-02-08 12:38

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.

查看更多
Root(大扎)
4楼-- · 2019-02-08 12:49
if ((instance?.Val).GetValueOrDefault() != 0)  

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

查看更多
登录 后发表回答