printing all contents of array in C#

Padraic Cunningham picture Padraic Cunningham · Apr 28, 2013 · Viewed 258.9k times · Source

I am trying to print out the contents of an array after invoking some methods which alter it, in Java I use:

System.out.print(Arrays.toString(alg.id));

how do I do this in c#?

Answer

Hossein Narimani Rad picture Hossein Narimani Rad · Apr 28, 2013

You may try this:

foreach(var item in yourArray)
{
    Console.WriteLine(item.ToString());
}

Also you may want to try something like this:

yourArray.ToList().ForEach(i => Console.WriteLine(i.ToString()));

EDIT: to get output in one line [based on your comment]:

 Console.WriteLine("[{0}]", string.Join(", ", yourArray));
 //output style:  [8, 1, 8, 8, 4, 8, 6, 8, 8, 8]

EDIT(2019): As it is mentioned in other answers it is better to use Array.ForEach<T> method and there is no need to do the ToList step.

Array.ForEach(yourArray, Console.WriteLine);