Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Array.ToString() provide a useful output?

Tags:

c#

If I have an array and perform a ToString() does that just string together the array values in one long comma seperated string or is that not possible on an array?

like image 728
PositiveGuy Avatar asked Feb 11 '10 15:02

PositiveGuy


People also ask

What does array toString do?

toString(): Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets (“[]”). Adjacent elements are separated by the characters “, ” (a comma followed by a space).

Does toString work on arrays?

Description. The Array object overrides the toString method of Object . The toString method of arrays calls join() internally, which joins the array and returns one string containing each array element separated by commas. If the join method is unavailable or is not a function, Object.

What does toString () do in Java?

The toString method is used to return a string representation of an object. If any object is printed, the toString() method is internally invoked by the java compiler. Else, the user implemented or overridden toString() method is called.

What is the use of toString method in C#?

Object. ToString is the major formatting method in the . NET Framework. It converts an object to its string representation so that it is suitable for display.


2 Answers

Option 1

If you have an array of strings, then you can use String.Join:

string[] values = ...;  string concatenated = string.Join(",", values); 

Option 2

If you're dealing with an array of any other type and you're using .NET 3.5 or above, you can use LINQ:

string concatenated = string.Join(",",                           values.Select(x => x.ToString()).ToArray()); 
like image 97
Adam Robinson Avatar answered Sep 20 '22 11:09

Adam Robinson


You can certainly do that, but it's not the default behaviour. The easiest way to do that (from .NET 3.5 anyway) is probably:

string joined = string.Join(",", array.Select(x => x.ToString()).ToArray()); 

MoreLINQ has a built-in method to do this:

string joined = array.ToDelimitedString(); 

or specify the delimited explicitly:

string joined = array.ToDelimitedString(","); 
like image 28
Jon Skeet Avatar answered Sep 22 '22 11:09

Jon Skeet