[Journal - ToString Revisited]

ToString Revisited

Sunday, December 26, 2004

While the documentation for ToString() says the method is intended to provide debugging output, this isn't the only way the method is used in practice. I've come up with at least three - not mutally exclusive - categories, not including the default behaviour implemented in System.Object:

First, debugging output. Examples include control classes (all demos done with WebEdit's code interpreter, which automatically ToString's any expression):

code:WebEditApp.MainForm
Gregor.WebEdit.FMain, Text: WebEdit.NET - journal.htm*

Then, there are simple data type conversions, such as from the builtin primitive types to String, or from things like StringBuilders or Guids. Here, the result is usable in any way the app sees fit:

code:System.Guid.NewGuid()
d2af5475-f330-4171-99fb-7b055980a5bb

Then, there are cases where the textual representation is suitable for program output, that is, it may end up in the user interface (localization issues aside). Typically, value types will fall into this category (because they usually have a simple textual representation):

code:System.DateTime.Now
26.12.2004 09:07:42

Also note that some control classes, such as ComboBox or ListBox, allow exploiting that behaviour, in that they simply call ToString() on each item for display, although more advanced binding options are available.