How to pass object[] to Activator.CreateInstance(type, params object[])
Asked Answered
T

2

9

I have a class which contains an empty constructor and one that accepts an array of objects as its only parameter. Something like...

public myClass(){ return; }
public myClass(object[] aObj){ return; }

This is the CreateInstance() method call that I use

object[] objectArray = new object[5];

// Populate objectArray variable
Activator.CreateInstance(typeof(myClass), objectArray);

it throws System.MissingMethodException with an added message that reads "Constructor on type 'myClass' not found"

The bit of research that I have done has always shown the method as being called

Activator.CreateInstance(typeof(myClass), arg1, arg2);

Where arg1 and arg2 are types (string, int, bool) and not generic objects. How would I call this method with only the array of objects as its parameter list?

Note: I have tried adding another variable to the method signature. Something like...

public myClass(object[] aObj, bool notUsed){ return; }

and with this the code executed fine. I have also seen methods using reflection which were appropriate but I am particularly interested in this specific case. Why is this exception raised if the method signature does in fact match the passed parameters?

Tutto answered 26/8, 2014 at 18:54 Comment(0)
W
14

Cast it to object:

Activator.CreateInstance(yourType, (object) yourArray);
Warship answered 26/8, 2014 at 18:56 Comment(4)
If his constructor takes an array, then that is a single item of the CreateInstance array, so it should be a nested array inside an item of the outer array.Organology
@AaronLS: It is nested, because the parameter is declared with params.Warship
Yes true, I was taking it a bit too literally probably.Organology
I see now so the object array should be passed as a single parameter thanks guys!Tutto
O
7

Let's say you have constructor:

class YourType {
   public YourType(int[] numbers) {
      ...
   }
}

I believe you would activate like so by nesting your array, the intended parameter, as a item of the params array:

int[] yourArray = new int[] { 1, 2, 4 };
Activator.CreateInstance(typeof(YourType ), new object[] { yourArray });
Organology answered 26/8, 2014 at 19:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.