When is it appropriate to override ToString?

Microsoft .NET

This question was asked on StackOverflow. Because my answer was upvoted well, I decided include it as a blog post.

First, let’s talk about what ToString actually is. The ToString method lives in System.Object, and because System.Object is the base class for all objects in C#, all objects have the ToString method. Some objects expose ToString overloads that accept parameters like CultureInfo, or formatting options, but for the most part most objects will have the default overload that accepts no parameters.

ToString was designed to do one thing: display a representation of an objects state. This is explicitly why it lives in System.Object. That is the only use for ToString, and it should be used. It should not be used to do anything else like change an objects state or apply behaviors.

These are the official guidelines from the .NET Development Series from Microsoft, specifically included in the Framework Design Guidelines book. I highly recommend you buy and read it in full, multiple times.

AVOID throwing exceptions from ToString

CONSIDER returning a unique string associated with the instance.

CONSIDER having the output of ToString be a valid input for any parsing methods on this type.

DO ensure that ToString has no observable side effects.

DO report security-sensitive information through an override of ToString only after demanding an appropriate permission. If the permission demand fails, return a string excluding security-sensitive information.

The Object.ToString method is intended to be used for general display and debugging purposes. The default implementation simply provides the object type name. The default implementation is not very useful, and it is recommended that the method be overridden.

DO override ToString whenever an interesting human-readable string can be returned. The default implementation is not very useful, and a custom implementation can almost always provide more value.

DO prefer a friendly name over a unique but not readable ID.

DO try to keep the string returned from ToString short. The debugger uses ToString to get a textual representation of an object to be shown to the developer. If the string is longer than the debugger can display, the debugging experience is hindered.

DO string formatting based on the current thread culture when returning culture-dependent information.

DO provide overload ToString(string format), or implement IFormattable, if the string return from ToString is culture-sensitive or there are various ways to format the string. For example, DateTime provides the overload and implements IFormattable.

DO NOT return an empty string or null from ToString

Leave a Comment

Your email address will not be published.