Found an interesting issue that following code runs with a different result:
char c = 'a'; c += 'a'; //passed c = c + 'a'; //Cannot implicitly convert type 'int' to 'char'. An explicit conversion exists (are you missing a cast?)
Is there any difference between a += b
and a=a+b
, or just compiler's code check missed it?
My point is why char += char
can pass the code check while char = (char+char)
considered char = int
?
C# Specification, Section 7.17.2 Compound assignment:
An operation of the form
x op= y
is processed by applying binary operator overload resolution (§7.3.4) as if the operation was writtenx op y
. Then,...
• Otherwise, if the selected operator is a predefined operator, if the return type of the selected operator is explicitly convertible to the type of
x
, and ify
is implicitly convertible to the type ofx
or the operator is a shift operator, then the operation is evaluated asx = (T)(x op y)
, whereT
is the type ofx
, except thatx
is evaluated only once
And that's exactly the situation we have here. The return type of the operation is int
but the types of x
and y
are both char
, and so an extra cast is automatically inserted for us.
(I believe this rule exists because there's nowhere for you to be able to insert an explicit cast yourself and it's kind of "expected" to work, especially in cases where x
and y
are the same type)
In the second case it is the assignment that is failing, not the calculation itself. If you explicitly cast the result in the second line to a char it works fine and indeed the following three lines generate identical IL:
c += (char)1; c = (char)(c + (char)1); c = (char)(c + 1);
So yes. There is a difference.
Note in the third line I didn't bother casting the 1
to char
since the calculation will just convert it back to an int anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With