Tuesday, April 12, 2005 2:50 PM
pgolde
ToString() on collections
I got a lot of great feedback on ToString and how it should work on collections. Based on that feedback, I've modified my implementation some and made it significantly better, I think:
1) Several people raised concerns that having ToString return a representation of the collection contents could drastically slow debugging for large collections, because the debugger internally calls ToString to display the value. For small collections, this is a huge plus, because you can see the collection contents directly in the debugger. For large collections, though, the returned string is too long to usefully look at, and the debugger might become very slow having to deal with all that data.What I did was use the new DebuggerDisplay attribute to specify a custom debugger display function. The returned format is similar to how ToString() looks ({1,2,3}), but is limited to around 250 characters. After this, it just puts a “...“ in the returned string. This gives the advantages of the ToString functionality in debugging, but doesn't negatively impact debugging in large collections.
2) Several people indicated the desire to customize the look of the returned string, possible by using a different separator than comma, or different string and end character other than braces. To address this, I added an static method to Algorithms:
string ToString<T>(IEnumerable<T> collection, bool recursive, string start, string separator, string end)
This method converts any enumerable collection to a string, and allows complete control over the separator string, as well as the start and end strings. The boolean recursive parameters determines whether contained collections are converted to a string via a recursive call or not.
Thanks to everyone for their feedback!