Cherno
Cherno

Reputation: 69

How to create an array with elements of type specified by a Type instance

I have a FieldInfo, and I know it's an array so I use its value to declare an Array instance, and also get the type of the array elements:

void Test(object baseInstance, FieldInfo baseInstanceField) {
    Array a = (Array)baseInstanceField.GetValue(baseInstance);
    Type elementType = TypeSystem.GetElementType(baseInstance.GetType());
}

Now I want to initialize a new array of type elementType with a specific length using reflection. How do I do this? I later will have to access the elements of this new array.

elementType[] newArray = new elementType[34]; //doesn't work

The type or namespace name `elementType' could not be found. Are you missing a using directive or an assembly reference?

Upvotes: 0

Views: 47

Answers (1)

Ondrej Tucny
Ondrej Tucny

Reputation: 27962

Obviously it doesn't work because instead of a type definition you are providing a variable (of a Type type, which is irrelevant here).

The Array class has a method to create an array like you need: Array.CreateInstance(Type, int):

var newArray = Array.CreateInstance(elementType, 34);

Upvotes: 1

Related Questions