About implicitly convert type 'int' to 'char', why it is different between `s[i] += s[j]` and `s[i] = s[i]+s[j] `

Eri*_*sui 24 c#

The sample code for demo:

public void ReverseString(char[] s) {
  for(int i = 0, j = s.Length-1; i < j; i++, j--){
        //s[i] = s[i]+s[j]; //<-- error           
        s[i] += s[j];       //<-- ok 

        s[j] = (char)(s[i] - s[j]); //<-- cast
        s[i] -= s[j];
    }
}
Run Code Online (Sandbox Code Playgroud)

As the above code snippet, while s[i] += s[j] is fine without any error. Its equivalent statement s[i] = s[i]+s[j] will cause error as follows

error CS0266: Cannot implicitly convert type 'int' to 'char'. An explicit conversion exists (are you missing a cast?

My question is what's their difference and why. Thanks in advance.

Jon*_*eet 35

Its equivalent statement s[i] = s[i]+s[j] will cause error as follows

It's not an equivalent statement, although I can understand why you'd expect it to be. From section 12.18.3 of the C# 5 ECMA standard, around compound assignment:

An operation of the form x op= y is processed by applying binary operator overload resolution (§12.4.5) as if the operation was written x op y. Then,

  • If the return type of the selected operator is implicitly convertible to the type of x, the operation is evaluated as x = x op y, except that x is evaluated only once.
  • 否则,如果选择的运算符是预定义的运算符,则如果选择的运算符的返回类型可以显式转换为的类型x,并且如果y可以隐式转换为的类型,x或者该运算符是shift运算符,则该运算将被评估为x = (T)(x op y),其中T的类型是x,但x仅被评估一次。

第二点是这里发生的事情。有没有运营商增加char值加在一起-有什么int +(int, int)运营商,这是何等的选择-而且有明确的转换,从intchar

所以这:

s[i] += s[j];
Run Code Online (Sandbox Code Playgroud)

更相当于

s[i] = (char) (s[i] + s[j]);
Run Code Online (Sandbox Code Playgroud)

...可以编译。