views:

874

answers:

2

I'm trying to deserialize an array of an type unknown at compile time. At runtime I've discovered the type, but I don't know how to create an instance.

Something like:

Object o = Activator.CreateInstance(type);

which doesn't work because there is no parameterless constructor, Array doesn't seem to have any constructor.

+9  A: 

Use Array.CreateInstance.

Jon Skeet
Slight problem with that. If I know that the type is a System.String[] and I Array.CreateInstance() I get a System.String[][]
CrashCodes
Type.GetElementType()
CrashCodes
Yes, you pass in the *element* type, not the final array type.
Jon Skeet
+3  A: 

You can use one of Array's CreateInstance overloads e.g.:-

object o = Array.CreateInstance(type, 10);
AnthonyWJones