I have searched both Google and this site to find an answer. I have also read it in my class book, but I still don’t understand how it is applied.
Here is what I know:
-
It is used to display what an object knows about itself.
-
It can be used to format the output about what it knows about itself.
-
It has be be overridden in the method to be used.
Thinking that you have a class like:
Using this:
will reveal all the internals of the class. Actually it is best used for quickly retrieving public fields of the class in a pre-formatted manner (thus effectively converting the data encapsulated in the class into a string).
Also here is a very useful advice from the book Pro C# 2010 and the .NET 4 Platform: “Many classes (and structures) that you create can benefit from overriding ToString() in order to return a string textual representation of the type’s current state. This can be quite helpful for purposes of debugging (among other reasons). How you choose to construct this string is a matter of personal choice; however, a recommended approach is to separate each name/value pair with semicolons and wrap the entire string within square brackets. However, always remember that a proper ToString() override should also account for any data defined up the chain of inheritance. When you override ToString() for a class extending a custom base class, the first order of business is to obtain the ToString() value from your parent using the base keyword. Once you have obtained your parent’s string data, you can append the derived class’s custom information.”