5

I want to get 'array type' of a type at run time. I do not need the instance of the array, just Type. I currently use the below method.

    private Type GetArrayType(Type elementType)
    {
        return Array.CreateInstance(elementType, 0).GetType();
    }

Is there any better solution without creating the instance of the array?

Note: I cannot use Type.GetType(elementType.FullName + "[]") because I create the element Type at runtime by Reflection.Emit. According to MSDN it requires dynamic assembly to be saved on disk which I do not want to do.

0

1 Answer 1

11

Yes, you can use Type.MakeArrayType.

Returns a Type object representing a one-dimensional array of the current type, with a lower bound of zero.

private Type GetArrayType(Type elementType)
{
    return elementType.MakeArrayType();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Seems like I need a rest... I cannot tell how I got lost in static methods of Array and Type and never thought about instance methods (:
I agree that some of the choices on those types of making methods instance/static are quite perplexing.

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.