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 !=
.
Save this answer. Show activity on this post. So what does return user != null actually return when it is null and when it is not. It simply evaluates the expression. If user is null it returns false and if user isn't null, it returns true .
The nullish coalescing operator ( ?? ) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined , and otherwise returns its left-hand side operand.
Null-conditional Operatoronly evaluates if the part to the left is not null. Otherwise, the code returns null. So, in the case above, item?. Name evaluates to null, but it does not throw an exception because there is no attempt to access a member on a null reference.
The unary postfix ! operator is the null-forgiving, or null-suppression, operator. In an enabled nullable annotation context, you use the null-forgiving operator to declare that expression x of a reference type isn't null : x! . The unary prefix ! operator is the logical negation operator.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With