Every class in .NET should have a meaningful ToString method. ToString magically and automatically converts an object into a human-readable string representation of itself. It’s not quite serialization, but it’s certainly a close cousin.
using System;
class ToStringExample1 {
public static void Main()
{
int x = 0;
int y = 0;
try
{
y = 10/x;
}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex.Message);
}
}
}
If you do this, all you’ll get is the exception message Attempted to divide by zero. Good luck troubleshooting your application on that meager bit of information! But what if we change the last line to use ToString instead?
// Compile and execute from the command line
using System;
class ToStringExample2 {
public static void Main()
{
int x = 0;
int y = 0;
try
{
y = 10/x;
}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex.ToString());
}
}
}
When compiled in debug mode, we now get an automatically generated string representation of that particular Exception object:
System.DivideByZeroException: Attempted to divide by zero.
at ConsoleApplication1.Program.Main(String[] args)
in C:\Program.cs:line 15
That’s a lot more helpful—you could actually diagnose a problem with this detailed exception information by exploiting the ability of ToString to force the computer to provide human-readable output.
Discussion
Unfortunately, not all .NET classes have good ToString methods. If you have a DataSet, you might naturally try calling DataSet.ToString. Guess what you’ll get when you do?
System.Data.DataSet
That’s utterly useless. You might’ve expected something like this:
+—————————————————–+
| DataSet1 |
+—————————————————–+
| Table1 |
+—————————————————–+
| field01 | field02 | field03 | field04 | field05 |
+—————————————————–+
| 1 | first | NULL | NULL | NULL |
| 2 | second | foo | 2006-10-31 | 10:30:00 |
| 3 | third | bar | 2006-10-31 | 10:30:01 |
+—————————————————–+
This seems perfectly logical to me, but DataSet.ToString doesn’t work that way out of the box.
When you’re creating your own classes, include ToString methods that make sense and produce human-readable output, even if the only human who will ever see that output is another programmer. If you’re working with someone else’s classes, consider overriding the ToString implementation to obtain the proper behavior that should have been present in the first place.