ni3.net
ni3.net

Reputation: 387

How "object.ToString()" evaluate in string concatenate statement?

My question is how "object.ToString()" method evaluate in string concatenate statement?.

I mean if write code like-:

class Employee
{
    public string Name{get; set;}

    public override string ToString()
    {
        return string.Format("Employee Name {0}", Name);
    }
}

static void Main()
{
    Employee emp = new Employee() {Name = "Ni3"};
    string result = "Result = " + emp;

    Console.WriteLine(result);
}

it yields -

Result = Employee Name Ni3 

so compiler transforms the statement like this -:

string result= String.Concat("Result = ",emp.ToString());

or there is another reason.

Upvotes: 0

Views: 202

Answers (1)

Hans Kesting
Hans Kesting

Reputation: 39284

Not quite, you are using the overload that uses two object parameters.

And this method calls .ToString() on those objects, after a null-check. See the remarks section:

The method concatenates arg0 and arg1by calling the parameterless ToString method of arg0 and arg1; it does not add any delimiters.
String.Empty is used in place of any null argument.
If either of the arguments is an array reference, the method concatenates a string representing that array, instead of its members (for example, "System.String[]").

Upvotes: 4

Related Questions