Search code examples
c#.netvisual-studioclassoverriding

Why does this happen when we override the ToString() method in a class?


I created a Person class and overrode some properties and constructor method and override ToString() method.

enter image description here

And I defined another class MyClass<T1> generically and created a field called a and the constructor method and the print method of field a.

enter image description here

And inside the main method, I created a new object of the Person class called class1 and filled the properties related to the Person class and called the print method through the class1 object.

enter image description here

And I am given the below output.

enter image description here

Why did this happen?

I know it's because of overriding ToString() but I don't understand it. :(


Solution

  • .ToString() method is called by MyClass<T>.Print() when it is calling Console.WriteLine. You pass your Person into Console.WriteLine as parameter for a call to format and print string (do you see {0} placeholder in Console.WriteLine first argument?). Inside it calls string.Format to render the string and this is the place where your overriden ToString() implementation is called.

    You can set a breakpoint inside ToString() method, run the debugger and look through the callstack, to find actual callers of your method.