Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are three virtual methods that IMHO should have never been added to System.Object...</p> <ul> <li>ToString()</li> <li>GetHashCode()</li> <li>Equals()</li> </ul> <p>All of these could have been implemented as you suggest with an interface. Had they done so I think we'd be much better off. So why are these a problem? Let's just focus on ToString():</p> <ol> <li>If ToString() is expected to be implemented by someone using ToString() and displaying the results you have an implicit contract that the compiler cannot enforce. You assume that ToString() is overloaded, but there is no way to force that to be the case.</li> <li>With an IStringable you would only need to add that to your generic type-constraint or derive your interface from it to require it's usage on implementing objects.</li> <li>If the benefit you find in overloading ToString() is for the debugger, you should start using [System.Diagnostics.DebuggerDisplayAttribute].</li> <li>As for needing this implementation for converting objects to strings via String.Format(), and/or Console.WriteLine, they could have deferred to the System.Convert.ToString(object) and checked for something like 'IStringable', failing over to the type's name if not implemented.</li> <li>As Christopher Estep points out, it's culture specific. </li> </ol> <p>So I guess I stand alone here saying I hate System.Object and all of it's virtual methods. But I do love C# as a whole and overall I think the designers did a great job.</p> <p>Note: If you intend to depend upon the behavior of ToString() being overloaded, I would suggest you go ahead and define your IStringable interface. Unfortunatly you'll have to pick another name for the method if you really want to require it.</p> <p><strong>more</strong></p> <p>My coworkers and I were just speaking on the topic. I think another big problem with ToString() is answering the question "what is it used for?". Is it Display text? Serialization text? Debugging text? Full type name?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload