2

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.

1
  • In your example, there is no way for enumerableType to have anything other than exactly one generic argument. The T value here is the source of your confusion, it does not represent the ultimate ElementType of the array, but rather the Type of the top-level inner nested collection, which could be an Array type, or some other type of enumerable. Commented Apr 23, 2024 at 5:40

1 Answer 1

4

Given that you know you are working with an Array via your check of IsArray, you can cast the enumerable to an Array and get the array bounds as follows:

private static Int32[] GetArrayBounds(Array value)
{
    var bounds = new Int32[value.Rank];
    for (var i = 0; i < value.Rank; i++)
        bounds[i] = value.GetLength(i);

    return bounds;
}

Where Rank tells you the number of dimensions in the array, and then subsequent calls to GetLength for a given dimension will tell you the size of that particular dimension.

Sign up to request clarification or add additional context in comments.

1 Comment

@Romoku I specifically didn't ask about jagged arrays, as there is no way to give a single size to the interior arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.