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#?
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#?
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, becauseIEnumerable<T>
is covariant on T:(I don't think you'd use this other than in test code.)
this is the easiest way that you could print the String by using array!!!
Due to having some downtime at work, I decided to test the speeds of the different methods posted here.
These are the four methods I used.
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
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:
-> 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.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.
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.
If you had your own class Foo, you could override ToString() like:
Another approach with the
Array.ForEach<T> Method (T[], Action<T>)
method of theArray
classThat takes only one iteration compared to
array.ToList().ForEach(Console.WriteLine)
which takes two iterations and creates internally a second array for theList
(double iteration runtime and double memory consumtion)