Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If the left operand to the ?? operator is not null, does the right operand get evaluated?

Tags:

operators

c#

.net

I'm looking at using the ?? operator (null-coalescing operator) in C#. But the documentation at MSDN is limited.

My question: If the left-hand operand is not null, does the right-hand operand ever get evaluated?

like image 523
Antarr Byrd Avatar asked Sep 24 '14 18:09

Antarr Byrd


People also ask

Why does the??= operator not evaluate its right-hand operand?

The ??= operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null. The left-hand operand of the ??= operator must be a variable, a property, or an indexer element. In C# 7.3 and earlier, the type of the left-hand operand of the ?? operator must be either a reference type or a nullable value type.

What is the difference between right operand and left operand?

The operator stores the value of the right operand expr in the object designated by the left operand lvalue. The left operand must be a modifiable lvalue. The type of an assignment operation is the type of the left operand.

How do you assign the value of the left operand?

If the left operand is a class type, that type must be complete. The copy assignment operator of the left operand will be called. If the left operand is an object of reference type, the compiler will assign the value of the right operand to the object denoted by the reference.

Why does&&evaluate the left operand in JavaScript?

The call to alert returns undefined (it just shows a message, so there’s no meaningful return). Because of that, && evaluates the left operand (outputs 1 ), and immediately stops, because undefined is a falsy value.


1 Answers

As ever, the C# specification is the best place to go for this sort of thing.

From section 7.13 of the C# 5 specification (emphasis mine):

A null coalescing expression of the form a ?? b requires a to be of a nullable type or reference type. If a is non-null, the result of a ?? b is a; otherwise, the result is b. The operation evaluates b only if a is null.

There are more details around when any conversions are performed, and the exact behaviour, but that's the main point given your question. It's also worth noting that the null-coalescing operator is right-associative, so a ?? b ?? c is evaluated as a ?? (b ?? c)... which means it will only evaluate c if both a and b are null.

like image 171
Jon Skeet Avatar answered Sep 28 '22 06:09

Jon Skeet