I created a Person class and overrode some properties and constructor method and override ToString() method.
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.
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.
And I am given the below output.
Why did this happen?
I know it's because of overriding ToString() but I don't understand it. :(
.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.