Conventions for ToString

What are the conventions for overriding ToString() ? This class has both a Name property and an Id .

+4
source share
7 answers

You can link to the following links

Overriding System.Object.ToString () and implementing IFormattable

C # demystification for programming ToString method

How to: Override the ToString Method

My rule | 1. It must be synchronized with Equals and GetHashCode
2. It must be synchronized with the Parse method (if I provide)
3. Use IFormattable if formatting is required.

+1
source

Do what you need. There is no convention per se, as there is when redefining something like .Equals() and .GetHashCode() .

If you want to influence what appears in the debugger during a break at runtime, do not use ToString() - use DebuggerDisplayAttribute .

+5
source

I do not know about any convention. I usually print what seems appropriate in a textual context. Id may not be appropriate for your context.

My rule of thumb is that a ToString should reveal whether two objects are Equals or not.

+1
source

As far as I know, the conventions for ToString() inextricably linked between the conventions for the other 2 redefined methods on the object - GetHashCode and Equals .

That is, when Equals returns true, then the same hash code must be generated using GetHashCode . To add to this, I would say that when Equals returns true, ToString should return the same string.

+1
source

I believe that the implementation of ToString() should keep in mind three things:

  • A string representation should be readable by a person, for example. you can use it to display the log / console or, for example, to the DebuggerDisplay attribute .
  • If you have any Parse method in your class, it should be able to parse the result of a ToString call. In addition, myInstance.Equals(MyClass.Parse(myInstance.ToString())) must evaluate to true
  • If two instances are equal, their string representation should also be equal.
+1
source

There are several recommendations here:

http://msdn.microsoft.com/en-us/library/ms173154(v=vs.80).aspx

I think it comes down to how the class is intended to be used. For example, if it is displayed oriented, then the return should be relevant for users who can see it.

0
source

You must use a consistent and reusable solution for all ToString methods for the entire application. Manual code for a general ToStringHelper or use an external library such as a stateprinter project https://github.com/kbilsted/StatePrinter project

0
source

All Articles