I've two lines of coding as below
int? i = 1;
int j = i ?? 2 +1;
now "j is 1"
int? i = 1;
int j = (i ?? 2) +1;
now "j is 2"
Could you explain how?
Sure - it's simple a matter of precedence. The (Microsoft) C# specification lists operator precedence in section 7.3.1 (in the C# 4 and C# 5 specifications, anyway; it's 7.2.1 in the C# 3 spec), although that's only really an informative table - it's really governed by the grammar.
Anyway, the null-coalescing operator (??
) has lower precedence than the binary addition operator (+
) so your first code is equivalent to:
int? i = 1;
int j = i ?? (2 + 1);
As the value of i
is non-null, the right hand operand of the null-coalescing operator isn't even evaluated - the result of i ?? (2 + 1)
is just 1.
Compare that with your second example, where the null-coalescing operator expression again evaluates to 1, but then 1 is added to the result of that. It's effectively:
int tmp = i ?? 2; // tmp is now 1
int j = tmp + 1; // j is 2
Associativity is irrelevant here, has it only controls the ordering/grouping when an operand occurs between two operators with the same precedence.
See more on this question at Stackoverflow