简体   繁体   中英

Null-conditional operator and !=

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

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM