Common method for printing arrays and lists of any types

51,600

Solution 1

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"

Solution 2

Arrays and generic lists both 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
}

Solution 3

Here's an extension method appropriate for debugging:

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

Solution 4

public void printArray<T>(IEnumerable<T> a)
{    
   foreach(var i in a)
   {
        Console.WriteLine(i);
   }
}
Share:
51,600

Related videos on Youtube

shahensha
Author by

shahensha

I am doing Bachelor's in Information Technology. Just completed my second year. Out here to learn more about programming. I am a good learner and love logical thinking. :) EDIT: I have started my PhD in Computer Science. I wish to specialize in Artificial Intelligence

Updated on July 09, 2022

Comments

  • shahensha
    shahensha almost 2 years

    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.

  • Bonez024
    Bonez024 over 5 years
    Your in-parameter T[] binds you to using Arrays Only. If that is your intent you could validate entry into this method with a generic constraint. In most cases it would be best to use IEnumerable as "Arrays and generic lists both implement IEnumerable<T>" as Babcock has stated above. It's also worth noting that the "ToString" within your WriteLine is typically necessary / redundant as all objects within it are converted to string regardless.

Related