Question

I have an object that is of type Array (that is object.GetType().IsArray returns true). My question is how can I find out whether it is a jagged or a multidimensional array? Is there a way to serialize the array so that the code "doesn't know" the difference (using reflection)?

Note that the array is of arbitrary length/dimension. I was thinking that I could perhaps parse the Type.Name to search for [, (as in one part of [,,]) or [][] to distinguish between these -- but that still means I'll have two code paths for each case and I feel like there should be a better way to accomplish this than parsing type names.

For a jagged array, it seems easy enough to take the array and then keep indexing it using [] to iterate over all the elements, however, this approach does not work for multidimensional arrays.

Was it helpful?

Solution

A jagged array is an array of arrays. So all you have to do is look at the element type and check that it is an array as well:

    static bool IsJaggedArray(object obj) {
        var t = obj.GetType();
        return t.IsArray && t.GetElementType().IsArray;
    }

    static void Test() {
        var a1 = new int[42];
        Debug.Assert(!IsJaggedArray(a1));
        var a2 = new int[4, 2];
        Debug.Assert(!IsJaggedArray(a2));
        var a3 = new int[42][];
        Debug.Assert(IsJaggedArray(a3));
    }

Cast to Array and use the Rank property to find the number of dimensions for a multi-dimensional array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top