[Info] Object.ToString and IFormattable

Jun 28, 2014 at 1:47 PM
Edited May 14, 2016 at 7:25 PM

This article has been moved to GitHub!

The Object.ToString method should be used for debugging purposes only. The default implementation shows the object type name which is not very useful. Consider to override this method to provide better information for diagnostics and debugging. Please consider that logging infrastructures often use the ToString method as well and so you will find these text fragments in your log files.

Do not return localized text resources within the Object.ToString method. The reason is that the ToString method should always return something that the developer can understand. The developer might not speak all languages which the application supports.

Implement the IFormattable interface when you want to return a user-friendly localized text. This interface defines a ToString overload with the parameters ‘format’ and ‘formatProvider’. The ‘formatProvider’ helps you to format the text in a culture aware way.

Avoid to return information that could change over the lifetime of the object. There is no standardized mechanism to tell the user interface that it needs to recall ToString because the content has changed. For this scenario you should introduce a public string property together with the INotifyPropertyChanged interface.

Further readings
  1. Framework Design Guidelines (Second Edition) by Krzysztof Cwalina and Brad Abrams