#661 – Every Object Has A ToString Method
August 31, 2012 Leave a comment
Since every type inherits either directly or indirectly from System.Object, and System.Object has a ToString method, every object inherits a ToString method.
The ToString method is intended to return a string identifying or representing the object, i.e. that specific instance. This is true for both value types and reference types.
For built-in types, ToString generally returns what you’d expect. For example, for a System.Int32 (int), it returns the value of the integer.
For custom types, if you don’t override ToString and provide something more meaningful, ToString just returns a string representing the type of the object.
Dog kirby = new Dog("Kirby", 13); Cow bessie = new Cow("Bessie"); int i = 12; double d = 1.38e-23; DayOfWeek bestDay = DayOfWeek.Saturday; object o = new System.Object(); DateTime dt = new DateTime(1536, 5, 19); // ToString can be called explicitly, or is called // implicitly when passing object as string parameter Console.WriteLine(kirby.ToString()); // Explicit Console.WriteLine(bessie); // Implicit Console.WriteLine(i); Console.WriteLine(d); Console.WriteLine(bestDay); Console.WriteLine(o); Console.WriteLine(dt);