0

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?

1
  • I'm using C#. Sorry if I forgot to include that information. Commented Sep 30, 2016 at 17:56

1 Answer 1

1

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

1 Comment

Thanks, you are right. By using the CreateInstance method both for a new array as well as for elements to be included, I manged to do what I wanted. Thank you very much!

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.