Operator + has different overloads:
int + int = int
int + string = string
string + int = string
In Following Expression:
string str = 30 + 20 + 10 + "ddd";
Console.WriteLine(str);
First 30 + 20 got evaluates both are integers so output of operator will be integer which is 50.
Then 50 + 10 will be evaluated which both are again integers so integer will be output which is 60.
Then 60 + "ddd" which is integer + string operation the operator in this case output string so 60 + "ddd" will output 60ddd.
In Following Expression:
string str = "ddd" + 30 + 20 + 10;
Console.WriteLine(str);
First "ddd" + 30 got evaluates in which string + integer operation takes place so output will be ddd30.
Then ddd30 + 20 will get evaluated in which again string + integer operation takes place so output will be ddd3020.
Then ddd3020 + 10 will get evaluated in which again string + integer operation takes place so output will be ddd302010.
operator +(int, int)
andoperator((string)int, string)
is the cause of confusion. – Counterpoint+
between twoint
s and in the second expression, it's+
betweenstring
andint
. Due to associativity. – Babysitter