Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the operator precedence of C# null-coalescing (??) operator?

Tags:

I've just tried the following, the idea being to concatenate the two strings, substituting an empty string for nulls.

string a="Hello"; string b=" World"; 

-- Debug (amusing that ? is print, doesn't exactly help readability...)

 ? a ?? "" + b ?? ""  

-> "Hello"

Correct is:

? (a??"")+(b??"") "Hello World" 

I was kind of expecting "Hello World", or just "World" if a is null. Obviously this is todo with operator precedence and can be overcome by brackets, is there anywhere that documents the order of precedence for this new operator.

(Realising that I should probably be using stringbuilder or String.Concat)

Thanks.

like image 511
AndyM Avatar asked Feb 04 '09 12:02

AndyM


People also ask

What is the highest precedence in C language?

Operator precedence in C is used to determine the order of the operators to calculate the accurate output. Parenthesis has the highest precedence whereas comma has the lowest precedence in C.

Which has higher precedence in C * or and?

Order of Precedence in Arithmetic Operators ++ and -- (increment and decrement) operators hold the highest precedence. Then comes * , / and % holding equal precedence. And at last, we have the + and - operators used for addition and subtraction, with the lowest precedence.

Which operator has lowest precedence in C?

4) Comma has the least precedence among all operators and should be used carefully For example consider the following program, the output is 1.

What is the order of precedence for operators?

The logical-AND operator ( && ) has higher precedence than the logical-OR operator ( || ), so q && r is grouped as an operand. Since the logical operators guarantee evaluation of operands from left to right, q && r is evaluated before s-- .


1 Answers

Aside from what you'd like the precedence to be, what it is according to ECMA, what it is according to the MS spec and what csc actually does, I have one bit of advice:

Don't do this.

I think it's much clearer to write:

string c = (a ?? "") + (b ?? ""); 

Alternatively, given that null in string concatenation ends up just being an empty string anyway, just write:

string c = a + b; 

EDIT: Regarding the documented precedence, in both the C# 3.0 spec (Word document) and ECMA-334, addition binds tighter than ??, which binds tighter than assignment. The MSDN link given in another answer is just wrong and bizarre, IMO. There's a change shown on the page made in July 2008 which moved the conditional operator - but apparently incorrectly!

like image 50
Jon Skeet Avatar answered Oct 04 '22 02:10

Jon Skeet