Question regarding C#'s `List<>.ToString`

C#List

C# Problem Overview


Why doesn't C# List<>'s ToString method provide a sensible string representation that prints its contents? I get the class name (which I assume is the default object.ToString implementation) when I try to print a List<> object. Why is that so?

C# Solutions


Solution 1 - C#

The simple answer is: that's just the way it is, I'm afraid.

Likewise List<T> doesn't override GetHashCode or Equals. Note that it would have very little way of formatting pleasantly other than to call the simple ToString itself, perhaps comma-separating the values.

You could always write your own extension method to perform appropriate formatting if you want, or use the newer overloads of string.Join which make it pretty simple:

string text = string.Join(",", list);

Solution 2 - C#

I think the reason is, that it is unclear what it should actualy do.

Maybe do ToString on ever elemenat and separate them with comas? But what if someone wants semicolons? Or dashes? Or someone wants to enclose whole string in curly or normal braclets? Or somone wants to use different function to get textual representation of single element?

Few things to note: ToString should be used only for debuging purpouses. If you want to export your data into string, either override this behaviour in your class or make an utility class for it.

Also List is intended to store elements, not to provide their textual representation.

Solution 3 - C#

Because it's probably not that easy to implement.

A List<> can contain a lot of stuff. For example another List<> that contains a Dictionary<> that contains complex objects...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmissingfaktorView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#EuphoricView Answer on Stackoverflow
Solution 3 - C#gsharpView Answer on Stackoverflow