P. Avery
P. Avery

Reputation: 809

How can I determine the length of an array using typeof() in C#?

Can I use the typeof() method( 'Type' class ) to determine the length of an array?

I have a method like this:

public void Foo<T>(T data)
{
    Type t = typeof(T);
    if(t.isArray)
    {
        // determine array length here
        ...
    }
}

You'll notice that the input to the above method DOES NOT have the array modifier([]). This is because the input does not have to be an array. I already know that I can write two overloads for this method but would like to know how to utilize the 'Type' class...

Upvotes: 0

Views: 65

Answers (2)

Mike Zboray
Mike Zboray

Reputation: 40818

Note that System.Array is the base class for array types:

public void Foo<T>(T data)
{
    Type t = typeof(T);
    if(t.IsArray)
    {
        int length = ((Array)(object)data).Length;
    }
}

Upvotes: 2

Timothy Shields
Timothy Shields

Reputation: 79441

You can use dynamic to easily accomplish this.

public void Foo<T>(T data)
{
    Type t = typeof(T);
    if (t.isArray)
    {
        int length = ((dynamic)data).Length;
    }
}

Upvotes: 1

Related Questions