0

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.

1 Answer 1

4

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();
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Jon, I edited the question too (t.GetType() -> just t). I don't know why I didn't think of going "backwards" rather than starting at typeof(Array).
@Anders: You still won't get t == typeof(Array) - if that worked, you could just use typeof(Array) to start with :) You'll get a t which is assignment-compatible with Array though.
Ok, thanks. Just out of curiosity (I'll change the question so it mathes the answer later), how would a proper assert in the question look really? Simply Assert(t.IsArray()) perhaps? or did that assert not help the question at all :) ?
t.IsArray would work, yes. Or typeof(Array).IsAssignableFrom(t)

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.