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)
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.
Maybe you will understand it better without the use of the ?? operator
Scenario 1:
int? i = 1;
int j;
if (i != null)
{
//i is not null so this is hit
j = i;
}
else
j = 2 + 1;
}
So j = 1
Scenario 2:
int? i = 1;
int j;
if (i != null)
{
//i is not null so this is hit
j = i;
}
else
j = 2;
}
So j = 1
//No matter the result of the above if, 1 is always added.
j = j + 1;
So j = 2
int? i = 1;
int j = i ?? 2 + 1; //If I is null make j = to 3
Now j is 1
int? i = 1;
int j = (i ?? 2) + 1; //If I is null make j = 2 else make j = to 0 and then add 1
Now j is 2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.