Pretty Printing C# Collections with Reflection

Image for post
Image for post

I wrote another blog post a week ago on how to print the contents of C# collections for debugging purposes. Read that post to know the background. Essentially we want to write an improved ToString method for C# collections so that we see the contents and type of the collection.

To get a better idea about what we are trying to achieve, let’s take a look at this line of C# code:

var myList = new List<string>() { "one", "two", "three"};
Console.WriteLine(myList);

With the default ToString we get the following when we try to print a List:

System.Collections.Generic.List`1[System.String]

So just the type of our variable. Not very helpful for debugging our code. Instead we would like to get something along the lines of the following:

List[one, two, three]

With this we know the type of the collection as well as its contents.

I wrote an extension method called ToStringExt using reflection. The extension method is for ICollection<T> type which is implemented by all the standard collection types (List, Dictionary, HashSet, etc.). The code itself doesn’t look pretty… well because of reflection. You can check out the code in the companion git repository for this blog post located here. If you are curious about the implementation, look at ToStringExtsReflection.cs. If you just want to use the method in your programs, take a look at Program.cs.

Here is small snippet to see the extension method in action.

Note that the extension method works for any class that implements ICollection<T> interface. As far as I know, all the standard generic collections do implement that interface.

Reflection is the ultimate solution for achieving what we want. By using the runtime type of the object, we will get a nice print out of the collection and its contents.

Hope you find this useful for your debugging your code. Follow me to learn more about C# and Unity.

Happy Coding!

Written by

Software Engineer | Indie Game Developer | Founder of No Such Studio. Follow me to learn how to make video games with Unity. http://www.nosuchstudio.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store