This post will discuss how to print single-dimensional arrays in C#.

1. Using foreach loop

The foreach statement provides a simple, clean way to iterate through the elements of an array. The following example shows the usage of the foreach statement for printing single-dimensional arrays in C#.

Download  Run Code

 
The above code uses Console.WriteLine() which outputs each element on a separate line. To print each element on a single line, use Console.Write(), as shown below:

Download  Run Code

 
We can also use a for-loop to process elements in increasing index order, starting from index 0 till index Length - 1, as shown below: The solution handles trailing delimiting characters.

Download  Run Code

2. Convert to List

Another approach is to use the ToList() method to convert the array into a generic List<T> and then call its ForEach() method to perform the print operation on each element of the List.

Download  Run Code

 
This approach is not recommended as it includes the creation of the List as an intermediate step.

3. Using Array.ForEach() method

The recommended solution is to directly call ForEach() method of the Array class rather than using List<T>.ForEach(Action<T>) method. The Array.ForEach<T> method of the Array class performs the specified action on each element of the specified array.

Download  Run Code

4. Using String.Join() method

Another good alternative is to use the String.Join() method, which concatenates the elements of the specified array using the specified separator.

Download  Run Code

That’s all about printing an array in C#.

 
Also See:

Print a multidimensional array in C#