General method for printing arrays and lists of any type

Whenever I debug a piece of code that includes arrays or lists of int, double, string, etc., I prefer to print them sometimes. To do this, I write overloaded printArray / printList methods for different types.

eg,

I can have these 3 methods for printing arrays of various types.

public void printArray(int[] a); public void printArray(float[] b); public void printArray(String[] s); 

Although this works for me, I still want to know if it is possible to have a generic method that prints arrays / lists of any type. Can this also be expanded to an array / list of objects.

+7
source share
5 answers

There is a useful String.Join<T>(string separator, IEnumerable<T> values) method String.Join<T>(string separator, IEnumerable<T> values) . You can pass an array or list or any enumerable collection of any objects, since the objects will be converted to a string by calling .ToString() .

 int[] iarr = new int[] {1, 2, 3}; Console.WriteLine(String.Join("; ", iarr)); // "1; 2; 3" string[] sarr = new string[] {"first", "second", "third"}; Console.WriteLine(String.Join("\n", sarr)); // "first\nsecond\nthird" 
+32
source

Arrays and general lists implement IEnumerable<T> , so just use it as your parameter type.

 public void PrintCollection<T>(IEnumerable<T> col) { foreach(var item in col) Console.WriteLine(item); // Replace this with your version of printing } 
+5
source
 public void printArray<T>(IEnumerable<T> a) { foreach(var i in a) { Console.WriteLine(i); } } 
+1
source

you can create a generic method like this

  public static void print<T>(T[] data) { foreach (T t in data) { Console.WriteLine(t.ToString()); } } 
0
source

Here we use an extension method suitable for debugging:

 [Conditional("DEBUG")] public static void Print<T>(this IEnumerable<T> collection) { foreach(T item in collection) { Console.WriteLine(item); } } 
0
source

All Articles