167

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#?

Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • See very closely related https://stackoverflow.com/questions/10075751/how-does-the-tostring-method-work – Peter Duniho Mar 06 '21 at 01:32
  • 1
    a) Use F# (`printfn "%A\n" [| 1, 2, 3 |]`) or b) use Common Lisp (`(let ((arr #(1 2 3))) (print arr))`). After writing some SO answer in C# after many years of using other languages, I cannot believe that a generic output of structs and arrays is still not part of C#. – BitTickler Apr 19 '21 at 21:30

13 Answers13

293

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);
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
  • 3
    Note that .ToString is not necessary since WriteLine has various overloads including a fallback one that takes an Object. – Eren Ersönmez Apr 28 '13 at 17:02
  • 1
    I used alg.Id.ToList().ForEach(Console.WriteLine), that worked well thanks you. Is it possible to actually print it like: [8, 1, 8, 8, 4, 8, 6, 8, 8, 8] – Padraic Cunningham Apr 28 '13 at 17:09
  • @ErenErsönmez Yes. You are right. but what if the item was a custom class with its own `ToString` mechanism. – Hossein Narimani Rad Apr 28 '13 at 17:09
  • 1
    On `ForEach` approach use: `expected.ToList().ForEach(Console.WriteLine);` You may use a Method Reference instead of a lambda that will create a new useless anonymous method. – Miguel Gamboa Mar 09 '16 at 12:03
  • 1
    Creating a list with `ToList` just to use the `ForEach` method is a horrible practice IMHO. – juharr Aug 13 '19 at 14:07
  • 3
    anyway there is no need to copy and paste my answer into yours – fubo Aug 29 '19 at 06:23
  • What if the array is very big? Is there an easy way to split the one liner into multiple more readable lines? Thanks – toughQuestions Dec 03 '20 at 13:34
90

There are many ways to do it, the other answers are good, here's an alternative:

Console.WriteLine(string.Join("\n", myArrayOfObjects));
Matt Greer
  • 60,826
  • 17
  • 123
  • 123
  • I like this because fits well for me in a write to log:e.g. myArrayObjects is _validExtensions: Write2Log("Start blabla with the exenstions: " + string.Join("-", _validImgExtensions) + " and so on"); – Teo Feb 12 '20 at 11:40
  • I like this too as it fits well with logging; And if the array element is one of your objects you can override the `ToString()` and handle the formatting there. `var a = new [] { "Admin", "Peon" };_log.LogDebug($"Supplied roles are '{string.Join(", ", a)}'.");` – Aaron Oct 17 '20 at 07:15
27

The easiest one e.g. if you have a string array declared like this string[] myStringArray = new string[];

Console.WriteLine("Array : ");
Console.WriteLine("[{0}]", string.Join(", ", myStringArray));
Joseph
  • 789
  • 1
  • 9
  • 23
Nai
  • 430
  • 5
  • 15
24

I decided to test the speeds of the different methods posted here:

These are the four methods I used.

static void Print1(string[] toPrint)
{
    foreach(string s in toPrint)
    {
        Console.Write(s);
    }
}

static void Print2(string[] toPrint)
{
    toPrint.ToList().ForEach(Console.Write);
}

static void Print3(string[] toPrint)
{
    Console.WriteLine(string.Join("", toPrint));
}

static void Print4(string[] toPrint)
{
    Array.ForEach(toPrint, Console.Write);
}

The results are as follows:

 Strings per trial: 10000
 Number of Trials: 100
 Total Time Taken to complete: 00:01:20.5004836
 Print1 Average: 484.37ms
 Print2 Average: 246.29ms
 Print3 Average: 70.57ms
 Print4 Average: 233.81ms

So Print3 is the fastest, because it only has one call to the Console.WriteLine which seems to be the main bottleneck for the speed of printing out an array. Print4 is slightly faster than Print2 and Print1 is the slowest of them all.

I think that Print4 is probably the most versatile of the 4 I tested, even though Print3 is faster.

If I made any errors, feel free to let me know / fix them on your own!

EDIT: I'm adding the generated IL below

g__Print10_0://Print1
IL_0000:  ldarg.0     
IL_0001:  stloc.0     
IL_0002:  ldc.i4.0    
IL_0003:  stloc.1     
IL_0004:  br.s        IL_0012
IL_0006:  ldloc.0     
IL_0007:  ldloc.1     
IL_0008:  ldelem.ref  
IL_0009:  call        System.Console.Write
IL_000E:  ldloc.1     
IL_000F:  ldc.i4.1    
IL_0010:  add         
IL_0011:  stloc.1     
IL_0012:  ldloc.1     
IL_0013:  ldloc.0     
IL_0014:  ldlen       
IL_0015:  conv.i4     
IL_0016:  blt.s       IL_0006
IL_0018:  ret         

g__Print20_1://Print2
IL_0000:  ldarg.0     
IL_0001:  call        System.Linq.Enumerable.ToList<String>
IL_0006:  ldnull      
IL_0007:  ldftn       System.Console.Write
IL_000D:  newobj      System.Action<System.String>..ctor
IL_0012:  callvirt    System.Collections.Generic.List<System.String>.ForEach
IL_0017:  ret         

g__Print30_2://Print3
IL_0000:  ldstr       ""
IL_0005:  ldarg.0     
IL_0006:  call        System.String.Join
IL_000B:  call        System.Console.WriteLine
IL_0010:  ret         

g__Print40_3://Print4
IL_0000:  ldarg.0     
IL_0001:  ldnull      
IL_0002:  ldftn       System.Console.Write
IL_0008:  newobj      System.Action<System.String>..ctor
IL_000D:  call        System.Array.ForEach<String>
IL_0012:  ret   
pietrodito
  • 1,783
  • 15
  • 24
Daxtron2
  • 1,239
  • 1
  • 11
  • 19
10

Another approach with the Array.ForEach<T> Method (T[], Action<T>) method of the Array class

Array.ForEach(myArray, Console.WriteLine);

That takes only one iteration compared to array.ToList().ForEach(Console.WriteLine) which takes two iterations and creates internally a second array for the List (double iteration runtime and double memory consumtion)

fubo
  • 44,811
  • 17
  • 103
  • 137
  • 1
    I like your method the best, it's the second fastest as per my test but it's more versatile than the fastest method( in my opinion ). – Daxtron2 May 16 '18 at 13:41
7

Starting from C# 6.0, when $ - string interpolation was introduced, there is one more way:

var array = new[] { "A", "B", "C" };
Console.WriteLine($"{string.Join(", ", array)}");

//output
A, B, C

Concatenation could be archived using the System.Linq, convert the string[] to char[] and print as a string:

var array = new[] { "A", "B", "C" };
Console.WriteLine($"{new String(array.SelectMany(_ => _).ToArray())}");

//output
ABC
Ola Ström
  • 4,136
  • 5
  • 22
  • 41
Johnny
  • 8,939
  • 2
  • 28
  • 33
2

In C# you can loop through the array printing each element. Note that System.Object defines a method ToString(). Any given type that derives from System.Object() can override that.

Returns a string that represents the current object.

http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx

By default the full type name of the object will be printed, though many built-in types override that default to print a more meaningful result. You can override ToString() in your own objects to provide meaningful output.

foreach (var item in myArray)
{
    Console.WriteLine(item.ToString()); // Assumes a console application
}

If you had your own class Foo, you could override ToString() like:

public class Foo
{
    public override string ToString()
    {
        return "This is a formatted specific for the class Foo.";
    }
}
Eric J.
  • 147,927
  • 63
  • 340
  • 553
0

If you want to get cute, you could write an extension method that wrote an IEnumerable<object> sequence to the console. This will work with enumerables of any type, because IEnumerable<T> is covariant on T:

using System;
using System.Collections.Generic;

namespace Demo
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            string[] array  = new []{"One", "Two", "Three", "Four"};
            array.Print();

            Console.WriteLine();

            object[] objArray = new object[] {"One", 2, 3.3, TimeSpan.FromDays(4), '5', 6.6f, 7.7m};
            objArray.Print();
        }
    }

    public static class MyEnumerableExt
    {
        public static void Print(this IEnumerable<object> @this)
        {
            foreach (var obj in @this)
                Console.WriteLine(obj);
        }
    }
}

(I don't think you'd use this other than in test code.)

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • Took me a while to fully understand but that is very handy, I am used to Python and putting print statements in to help debug so this is good for me.Thanks – Padraic Cunningham Apr 28 '13 at 19:27
0

I upvoted the extension method answer by Matthew Watson, but if you're migrating/visiting coming from Python, you may find such a method useful:

class Utils
{
    static void dump<T>(IEnumerable<T> list, string glue="\n")
    {
        Console.WriteLine(string.Join(glue, list.Select(x => x.ToString())));
    }
}

-> this will print any collection using the separator provided. It's quite limited (nested collections?).

For a script (i.e. a C# console application which only contains Program.cs, and most things happen in Program.Main) - this may be just fine.

Tomasz Gandor
  • 8,235
  • 2
  • 60
  • 55
0

this is the easiest way that you could print the String by using array!!!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace arraypracticeforstring
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] arr = new string[3] { "Snehal", "Janki", "Thakkar" };

            foreach (string item in arr)
            {
                Console.WriteLine(item.ToString());
            }
            Console.ReadLine();
        }
    }
}
0

If it's an array of strings you can use Aggregate

var array = new string[] { "A", "B", "C", "D"};
Console.WriteLine(array.Aggregate((result, next) => $"{result}, {next}")); // A, B, C, D

that way you can reverses the order by changing the order of the parameters like so

Console.WriteLine(array.Aggregate((result, next) => $"{next}, {result}")); // D, C, B, A
BluePositive
  • 21
  • 1
  • 9
0

You can use for loop

    int[] random_numbers = {10, 30, 44, 21, 51, 21, 61, 24, 14}
    int array_length = random_numbers.Length;
    for (int i = 0; i < array_length; i++){
        if(i == array_length - 1){
              Console.Write($"{random_numbers[i]}\n");
        } else{
              Console.Write($"{random_numbers[i]}, ");
         }
     }
-2

If you do not want to use the Array function.

public class GArray
{
    int[] mainArray;
    int index;
    int i = 0;

    public GArray()
    {
        index = 0;
        mainArray = new int[4];
    }
    public void add(int addValue)
    {

        if (index == mainArray.Length)
        {
            int newSize = index * 2;
            int[] temp = new int[newSize];
            for (int i = 0; i < mainArray.Length; i++)
            {
                temp[i] = mainArray[i];
            }
            mainArray = temp;
        }
        mainArray[index] = addValue;
        index++;

    }
    public void print()
    {
        for (int i = 0; i < index; i++)
        {
            Console.WriteLine(mainArray[i]);
        }
    }
 }
 class Program
{
    static void Main(string[] args)
    {
        GArray myArray = new GArray();
        myArray.add(1);
        myArray.add(2);
        myArray.add(3);
        myArray.add(4);
        myArray.add(5);
        myArray.add(6);
        myArray.print();
        Console.ReadKey();
    }
}
ugurpolat
  • 1
  • 2