Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does c# string evaluates its own value?

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!

like image 507
Russel Ledge Avatar asked Apr 05 '17 07:04

Russel Ledge


2 Answers

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"
like image 137
CodeCaster Avatar answered Oct 20 '22 18:10

CodeCaster


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

like image 41
MistyK Avatar answered Oct 20 '22 17:10

MistyK