Unable to find constructor by type; works in watch

This is the code I'm using:

Type type = /* retrieved Type */ object arg = /* something that evaluates to null */ MyClass obj = (MyClass)Activator.CreateInstance(type, arg); 

I get a failure that this constructor does not exist in type type .

However, when I put this in Watch in Visual Studio 2008:

 (MyClass)System.Activator.CreateInstance(type, null) 

he creates the object as usual.

I even tried replacing my code with the one I put in Watch. It works - the object is created.

My question is: what about this?

Edit: MyClass has no constructors - other than a regenerated constructor without parameters.

Edit 2: Using new object[0] instead of null still raises the same exception.

+4
source share
2 answers

You have a problem with the params .

Actual signature of the CreateInstance(Type, object[]) function. However, the fact that the object[] parameter is declared as params means that you can pass a variable number of arguments to the function, and these arguments will be collapsed into a new array or you can directly pass an array of objects.

When the compiler does overload resolution in the version where you pass null directly to the function, it does not convert the parameter to an array, since null is a valid value for this. However, when you pass a null object variable, overload resolution should turn this into an array of objects. This means that you are passing an array of objects with a single value that is null . The runtime then searches for a constructor with one argument, which is then passed null to.

This is why permission fails at runtime.

+2
source

Your code uses the following Activator.CreateInstance Method overload:

 public static Object CreateInstance( Type type, params Object[] args ) 

Pay attention to the params .

Now take a look at your code:

 Activator.CreateInstance(type, null) 

This passes the null reference as args . In this case, the method searches for a constructor without parameters.

 object arg = // ... Activator.CreateInstance(type, arg) 

This passes a singleton array containing a null reference as args , because arg declared as an object . In this case, the method is looking for a constructor with one parameter.

To avoid any ambiguity, call the method as follows:

 object[] args = null; // 0 parameters // - or - object[] args = new object[] { "Hello World" }; // 1 parameter var result = (MyClass)Activator.CreateInstance(type, args); 
+4
source

All Articles