#661 – Every Object Has A ToString Method

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);

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: