简体   繁体   中英

C# string + vs. +=

Why does string += char + int work differently to string = string + char + int ?

char c = '0';
int i = 123;
string s = "";
s += c + i;  // Evaluated as s = s + (c + i);
Console.WriteLine($"s: \"{s}\"");  // s: "171"

s = "";
s = s + c + i;  // Evaluated as s = (s + c) + i;
Console.WriteLine($"s: \"{s}\"");  // s: "0123"

Tested on C# 4.0-9.0.

As described in C# language reference :

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, ...

PS: this is real-life situation:

path += Path.AltDirectorySeparatorChar + fileId + ".txt";

int and char can be cast to each other in c#. char can be added to an int to produce an int, because ( link - emphasis added)

The char type supports comparison, equality, increment, and decrement operators. Moreover, for char operands, arithmetic and bitwise logical operators perform an operation on the corresponding character codes and produce the result of the int type .

For example:

'0' + 123 
// result: 171

And an int can be converted back into a char:

(char)48
// result: '0'

So when you try to concatenate with += , the int and char are evaluated to an int type since there is nothing telling them to do otherwise. Prepend with a string, however:

string s += "" + c + i;
// result: "0123"

Now the compiler, reading your expression from left to right, implicitly calls ToString on c and i , so no arithmetic operations occur, only string concatenation (That's why string s = s + c + i behaved differently).

Update

Per your comment:

Now I can reformulate my question:) Why s += c + i is equivalent to s += (c + i) instead of (s += c) + i

Everything after the += is evaluated before the concatenation (see Operator precedence and associativity ). Think of everything right of the = as its own variable. Essentialy:

var right = c + i;
var left = s;
s = left + right; // effectively same as s += c + i;

// or

s = s + (c + i /** everything on the right side in order here **/);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM