Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common method for printing arrays and lists of any types [duplicate]

Whenever I am debugging a piece of code which involves arrays or lists of ints, doubles, strings, etc/, I prefer printing them over sometimes. What I do for this is write overloaded printArray / printList methods for different types.

for e.g.

I may 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);

Though this works for me, I still want to know whether it is possible to have a generic method which prints arrays/lists of any types. Can this also be extended to array/list of objects.

like image 997
shahensha Avatar asked Mar 11 '12 13:03

shahensha


1 Answers

There is useful String.Join<T>(string separator, IEnumerable<T> values) method. You can pass array or list or any enumerable collection of any objects since objects will be converted to 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"
like image 99
Kirill Avatar answered Oct 11 '22 20:10

Kirill