This one’s really short, but really helpful in my experience. It’s a block of code that seems to make it into just about everything I’ve written in the last year.
In my opinion, it does no one any good if you call ToString() on a collection, and all you see is System.Collections.Generic.List`1 printed out to your console (or whatever). This is another opportunity for Microsoft to create something that is valuable to the human, instead of something that is valuable to the compiler. The first extension method is the one you’ll need. The other two extension methods shown are used by the first extension method.
public static class CollectionHelpers
{
public static string ToString<T>(this IEnumerable<T> collection, bool expandInternals)
{
if (collection.IsNullOrEmpty()) return "[]";
if (!expandInterals) return collection.ToString();
var internals = string.Join(", ", collection.ToArray());
return internals.Wrap("[", "]");
}
public static bool IsNullOrEmpty<T>(this IEnumerable<T> collection)
{
return (collection == null) || (!collection.Any());
}
public static string Wrap(this string source, string before, string after)
{
return string.Format("{0}{1}{2}", before, source, after);
}
}
Now, instead of seeing the type, which does no one any good, you will see the actual contents (or at least the ToString representation of the contents) of the collection.