3

Here is what I have

        int[] x = new int[10];

        Type type = x.GetType();
        if (type.IsArray)
        {
            Type typeOfElement = type.GetElementType();
            int length = 0; // how do I get array's length????
        }

Is there a way to determine length of array using Type?

4
  • In what language is this written on? Commented Jul 9, 2016 at 12:56
  • You'll have to use Type.GetProperty(). First read the Rank property to verify how many dimensions the array has. If you are happy with 1 then read the Length property. Commented Jul 9, 2016 at 12:58
  • 1
    @Hans Passant: I still need instance in this case, right? Commented Jul 9, 2016 at 13:02
  • Of course, these properties are not static. Commented Jul 9, 2016 at 13:06

4 Answers 4

2

Use Array.Length:

int[] x = new int[10];

Type type = x.GetType();
if (type.IsArray)
{
    int length = (x as Array).Length;
}

Edit: Just realized that you asked about getting the length from the type and not from the instance. You can't do that since your type will always be an array and it doesn't matter what sizes they have:

int[] arr1 = new int[10];
int[] arr2 = new int[11];

bool areEqual = arr1.GetType() == arr2.GetType(); // true
Sign up to request clarification or add additional context in comments.

1 Comment

And in the first interpretation you do not need GetType(), you can do: var a = x as Array; if (a != null) { var length = a.Length; /* ... */ }
1

There is no information on the type regarding the size of the array. It is just an array, nothing more.

So the only way to get the size is going back to the instance. There, and only there, you can find the size of the array.

You could do that by querying the Length property using reflection.

Comments

0

Using reflection, you cannot get length of array. You can access properties of the object, know their types and methods provided by that object(class). But you cannot recreate or know what was the lengths of an array by knowing just its type.

Comments

0

Arrays of different lengths will have identical types, for example new int[10] and new int[11] have identical (run-time) types.

This means you cannot reconstruct the length from the System.Type alone; you need the reference to the actual array instance.

Comments

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.