because of the precedence of the operators and the chosen overload of the +
operator. When you look at this line:
var d2 = s + 'd' + ' ' + "dynamic test 2";
for the first +
operator you have an int
and a char
on the two sides. Here the overload int operator +(int x, int y);
of the addition operator is chosen which will add the number and the char (which is implicitly converted into an int because behind the curtains it has a numeric representation of 'd'
). There you get a int
as result.
PaulF provided the link to the documentation which says to char:
The value of a Char object is a 16-bit numeric (ordinal) value.
this is the reason why the result is a number.
The second +
operator is treated in the same manner.
The third+
operator has a string of the other side, so the compiler calls the ToString
method implicitly on the int
variable and another overload of the addition operator is chosen, namely: string operator +(object x, string y);
which concatenates the two.
You can now determine the precedence using ( )
. In this line:
var d2 = s + ('d' + (' ' + "dynamic test 2"));
Here the third +
operator will be evaluated first, so the concatenation overload will be taken. The result is a string. The second operator will encounter again a string on the right hand side, so it will be the same context again, and again the ToString()
method will be called and the char
(turning into a string) will be concatenated. When reaching the first operator again the ToString()
method will be called (now on the int
, turning into a string) will be concatenated.
This post might give further help
EDIT
Here is the overview over all possible Addition operator overloads
In general the choice of the data types is determined the following way:
For an operation of the form x + y, binary operator overload resolution Section 7.2.4 is applied to select a specific operator implementation. The operands are converted to the parameter types of the selected operator, and the type of the result is the return type of the operator.
The documentation states for the string concatenation:
When one or both operands are of type string, the predefined addition operators concatenate the string representation of the operands.
The binary + operator performs string concatenation when one or both operands are of type string.