0

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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
ni3.net
  • 377
  • 4
  • 14

1 Answers1

4

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[]").

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111