Anders Forsgren
Anders Forsgren

Reputation: 11101

How do I create an instance of the Array type with a given ElementType?

How do I create a type object that represents the type of an array with a given element type?

Type t = MakeArrayType(elementType);  // How?

Such that

Assert(t.GetElementType() == elementType);

I can create a dummy instance of my requested array and then get the type from there. But I wonder if there is a way to get the type without creating the instance first?

object myArrayInstance = Array.CreateInstance(elementType, 0);
Type t = myArrayInstance.GetType();   // This is the desired type.

Upvotes: 0

Views: 821

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499830

If t refers to a Type, then t.GetType() will obviously be typeof(Type) or a subtype - not typeof(Array).

However, I suspect you want Type.MakeArrayType:

Type arrayType = elementType.MakeArrayType();

Upvotes: 4

Related Questions