Reputation: 12993
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 !=
.
Upvotes: 21
Views: 14466
Reputation: 53958
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.
Upvotes: 11
Reputation: 3161
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).
Upvotes: 13
Reputation: 34698
if ((instance?.Val).GetValueOrDefault() != 0)
the ? conditional operator will automatically treat the .Val property as a Nullable.
Upvotes: 2