Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird operator precedence with ?? (null coalescing operator)

Tags:

Recently I had a weird bug where I was concatenating a string with an int? and then adding another string after that.

My code was basically the equivalent of this:

int? x=10; string s = "foo" + x ?? 0 + "bar"; 

Amazingly enough this will run and compile without warnings or incompatible type errors, as will this:

int? x=10; string s = "foo" + x ?? "0" + "bar"; 

And then this results in an unexpected type incompatibility error:

int? x=10; string s = "foo" + x ?? 0 + 12; 

As will this simpler example:

int? x=10; string s = "foo" + x ?? 0; 

Can someone explain how this works to me?

like image 546
Earlz Avatar asked Jul 15 '10 19:07

Earlz


People also ask

What is a null coalescing operator used for?

A null coalescing operator, in C#, is an operator that is used to check whether the value of a variable is null.

What is null conditional and null coalescing?

In cases where a statement could return null, the null-coalescing operator can be used to ensure a reasonable value gets returned. This code returns the name of an item or the default name if the item is null. As you can see, this operator is a handy tool when working with the null-conditional operator.

When was Nullish coalescing operator added?

JavaScript made sure this can be handled with its nullish operator also known as the Null Coalescing Operator, which was added to the language with ECMAScript 2020. With it, you can either return a value or assign it to some other value, depending on a boolean expression.


1 Answers

The null coalescing operator has very low precedence so your code is being interpreted as:

int? x = 10; string s = ("foo" + x) ?? (0 + "bar"); 

In this example both expressions are strings so it compiles, but doesn't do what you want. In your next example the left side of the ?? operator is a string, but the right hand side is an integer so it doesn't compile:

int? x = 10; string s = ("foo" + x) ?? (0 + 12); // Error: Operator '??' cannot be applied to operands of type 'string' and 'int' 

The solution of course is to add parentheses:

int? x = 10; string s = "foo" + (x ?? 0) + "bar"; 
like image 96
Mark Byers Avatar answered Oct 22 '22 17:10

Mark Byers