First, what I'm trying to accomplish- I find the C# interactive window available with Roslyn to be very useful. One of it's more interesting features is that it can take any IEnumerable
and prints out its contents in a human readable form.
For example, typing:
var a = new[,] { {3, 4}, {5, 6} }; a
Will print:
int[2, 2] { { 3, 4 }, { 5, 6 } }
I'm trying to replicate this behavior in my own extension method on IEnumerable
(for debugging purposes). Printing the elements themselves is easy, the trouble I'm running into is how to get the array dimensions given only an IEnumerable<T>
.
This is what I have so far for getting the type's name and size:
private static String getFormattedTypeName<T>(IEnumerable<T> enumerable)
{
var enumerableType = enumerable.GetType();
var typeNameAndSize = new StringBuilder();
typeNameAndSize.Append(enumerableType.Name.Split('`').First());
var genericArguments = enumerableType.GetGenericArguments();
if (genericArguments.Length != 0)
{
typeNameAndSize.Append(String.Format("<{0}> ({1})",
String.Join(",", genericArguments.Select(t => t.Name)),
enumerable.Count()));
}
else if (enumerableType.IsArray)
{
//Can I get the length of each array dimension from the type???
}
return typeNameAndSize.ToString();
}
My question is what is the best way to get the dimensions of multi-dimensional arrays where my comment indicates? I don't see any methods on Type
which fit the bill.