Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

activator

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?

like image 956
Strahinja Vladetic Avatar asked Aug 26 '14 18:08

Strahinja Vladetic


People also ask

What is Activator CreateInstance c#?

The Activator. CreateInstance method creates an instance of a type defined in an assembly by invoking the constructor that best matches the specified arguments. If no arguments are specified then the constructor that takes no parameters, that is, the default constructor, is invoked.


2 Answers

Cast it to object:

Activator.CreateInstance(yourType, (object) yourArray);
like image 91
Tobias Brandt Avatar answered Sep 29 '22 05:09

Tobias Brandt


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 });
like image 20
AaronLS Avatar answered Sep 29 '22 04:09

AaronLS