简体   繁体   中英

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

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?

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);

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.

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM