Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null-conditional operator and !=

Tags:

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

like image 559
kennyzx Avatar asked Jun 28 '17 04:06

kennyzx


People also ask

What does != null mean in C#?

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 .

WHAT IS null check operator?

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.

IS null conditional statement?

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.

What is null forgiving operator?

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.


1 Answers

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

like image 108
Pablo notPicasso Avatar answered Nov 05 '22 00:11

Pablo notPicasso