Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a += b operator of char implemented same as a = a + b? [duplicate]

Tags:

c#

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?

like image 891
喵喵喵 Avatar asked Apr 06 '17 11:04

喵喵喵


Video Answer


2 Answers

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 written x 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 if y is implicitly convertible to the type of x or the operator is a shift operator, then the operation is evaluated as x = (T)(x op y), where T is the type of x, except that x 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)

like image 124
Damien_The_Unbeliever Avatar answered Sep 21 '22 19:09

Damien_The_Unbeliever


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.

like image 36
Chris Avatar answered Sep 22 '22 19:09

Chris