Search code examples
c#.netexpressionoperator-precedence

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!


Solution

  • 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"