Reputation: 1319
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?
Upvotes: 3
Views: 1584
Reputation: 61912
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.
Upvotes: 0
Reputation: 607
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.
Upvotes: 0
Reputation: 29836
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
Upvotes: 2
Reputation: 156928
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.
Upvotes: 1