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 is very fast in terms of execution time. Programs written and compiled in C execute much faster than compared to any other programming language. C programming language is very fast in terms of execution as it does not have any additional processing overheads such as garbage collection or preventing memory leaks etc.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With