How does a C # string evaluate an eigenvalue?

Why is this piece of code

string str = 30 + 20 + 10 + "ddd"; Console.WriteLine(str); 

creates 60ddd ,

and this one

 string str = "ddd" + 30 + 20 + 10; Console.WriteLine(str); 

produces ddd302010 ?

It seems to be very simple, but I can’t lower my head. Please show me the direction I can go in order to find a detailed answer.

Thanks!

+7
c # expression operator-precedence
source share
5 answers

The + operators in the expression you show have the same priority, because they are the same operator, so they are evaluated from left to right:

 30 + 20 + 10 + "ddd" -- + (int, int) returns (int)50 ------- + (int, int) returns (int)60 ------------ + (object, string) returns (string)"60ddd" 

Then for another case:

 "ddd" + 30 + 20 + 10 ----- + (string, object) returns (string)"ddd30" ---------- + (string, object) returns (string)"ddd3020" --------------- + (string, object) returns (string)"ddd302010" 
+11
source share

This is because the expression evaluates from left to right. In the first example, 30 + 20 + 10 gives you the string int + string (30 + 20 + 10) - int, "ddd" - string. In the second example, "ddd" + 30 is the string "ddd30", which adds "20" and "10" to it. It is all about order (unless you have paranthesis).

+2
source share

The + operator has different overloads:

int + int = int

int + string = string

string + int = string

In the following expression:

 string str = 30 + 20 + 10 + "ddd"; Console.WriteLine(str); 

The first 30 + 20 received the estimates as integers, so the operator output will be an integer of 50 .

Then 50 + 10 will be evaluated, which are both integers again, so an integer that is 60 will be displayed.

Then 60 + "ddd" , which is an integer + string , the operator in this case displays a string, so 60 + "ddd" will output 60ddd .

In the following expression:

 string str = "ddd" + 30 + 20 + 10; Console.WriteLine(str); 

The first "ddd" + 30 received grades in which the string + integer operation is performed, so the output will be ddd30 .

Then ddd30 + 20 will be evaluated, in which the string + integer operation is performed again, so the output will be ddd3020 .

Then ddd3020 + 10 will be evaluated, in which the string + integer operation is performed again, so the output will be ddd302010 .

+1
source share

It is rated from left to right. The first example contains numbers first, so it starts by calculating numbers. He then finds out that it should be evaluated as a string. The second example is the opposite. It starts with a line and continues with a line.

+1
source share

This is because the order of operations is from left to right. But binding is the last operation. To evaluate the value, the first expression must be calculated.

0
source share

All Articles