Deadhand Deadhand - 1 year ago 223
C# Question

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

I have a class which contains an empty constructor and one that accepts and 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
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?

Answer Source

Cast it to object:

Activator.CreateInstance(yourType, (object) yourArray);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download