Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

list

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?

like image 268
missingfaktor Avatar asked Feb 19 '11 11:02

missingfaktor


People also ask

Why is C very important?

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.


2 Answers

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); 
like image 173
Jon Skeet Avatar answered Sep 18 '22 14:09

Jon Skeet


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.

like image 35
Euphoric Avatar answered Sep 19 '22 14:09

Euphoric