Why does this snippet of code
string str = 30 + 20 + 10 + "ddd";
Console.WriteLine(str);
produces 60ddd
,
and this one
string str = "ddd" + 30 + 20 + 10;
Console.WriteLine(str);
produces ddd302010
?
Seems like it's very simple, but I can't get my head around it. Please, show me direction in which I can go in order to find a detailed answer.
Thanks!
The +
operators in the expression you show have equal precedence because they're the same operator, hence are evaluated left to right:
30 + 20 + 10 + "ddd"
-- + (int, int) returns (int)50
------- + (int, int) returns (int)60
------------ + (object, string) returns (string)"60ddd"
Then for the other case:
"ddd" + 30 + 20 + 10
----- + (string, object) returns (string)"ddd30"
---------- + (string, object) returns (string)"ddd3020"
--------------- + (string, object) returns (string)"ddd302010"
It's because an expression is evaluated from left side to right side. In the first example 30 + 20 + 10 gives you int + string (30 + 20 + 10) - int, "ddd" - string. In the second example "ddd" + 30 is a string "ddd30" that appends "20" and "10" to it. It's all about the order (unless you have paranthesis).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With