Information Technology Reference
In-Depth Information
The System.Object version returns the fully qualified name of the type.
It's useless information: "System.Drawing.Rect", "MyNamespace.Point",
"SomeSample.Size" is not what you want to display to your users. But that's
what you get when you don't override ToString() in your classes. You write
a class once, but your clients use it many times. A little more work when
you write the class pays off every time you or someone else uses it.
Let's consider the simplest requirement: overriding System.Object.ToString().
Every type you create should override ToString() to provide the most com-
mon textual representation of the type. Consider a Customer class with
three public properties:
public class Customer
{
public string Name
{
get ;
set ;
}
public decimal Revenue
{
get ;
set ;
}
public string ContactPhone
{
get ;
set ;
}
public override string ToString()
{
return Name;
}
}
The inherited version of Object.ToString() returns "Customer". That is
never useful to anyone. Even if ToString() will be used only for debugging
purposes, it should be more sophisticated than that. Your override of
Object.ToString() should return the textual representation most likely to
be used by clients of that class. In the Customer example, that's the name:
Search WWH ::




Custom Search