ToString Method
The C# object type, from which all other types derive, provides a ToString method. This means that whatever your
object is, it has a ToString method that delivers a string.
One thing that ToString is always good for is converting numbers to their string representation—a common task
in displaying numbers, among other things. For example, you can use the ToString method to display the first
four places of the expansion of Pi:
double theNumber = 3.1415;
MessageBox.Show(theNumber.ToString());
While the ToString method of any object will always deliver a string, it may not always be the string
you want. By definition, the ToString method of an object returns a string that represents the object.
The problem is that it is up to the implementer of a class to decide what is returned by objects based
on the class. Most of the time, ToString is implemented so that it returns something reasonable, but you
won’t know until you try.
For example, if you invoke a Form’s ToString method, you’ll get the fully qualified form name followed by
the literal “, Text:” followed by the contents of the Form’s Text property (its caption).
Now, most likely what you really wanted was the unqualified name of the Form—and it is true that you could
parse this out of the string returned by the ToString method—but the point stands that with complex objects
you need to be careful about exactly what ToString returns.
You should also bear in mind when creating your own classes that you are responsible for implementing the
ToString method in a useful way—other programmers using your class libraries will expect to use your
ToString method implementation, and be irritated if it doesn’t return what they expect.
|