This is the code I use:
Type type = /* retrieved Type */
object arg = /* something that evaluates to null */
MyClass obj = (MyClass)Activator.CreateInstance(type, arg);
I get a crash, that given constructor doesn’t exist on type type.
However, when I put this in Watch in Visual Studio 2008:
(MyClass)System.Activator.CreateInstance(type, null)
it creates the object as usual.
I even tried replacing my code with the one I put in the Watch. It works – object gets created.
My question: what’s up with that?
Edit: MyClass doesn’t have any constructors – apart from pregenerated parameterless constructor.
Edit 2: Using new object[0] instead of null still causes the same exception.
You’ve run into an issue with the
paramskeyword.The actual signature of the function is
CreateInstance(Type, object[]). However, the fact that theobject[]parameter is declared asparamsmeans that you can pass a variable number of arguments to the function and those arguments will get rolled into a new array, or you can directly pass an object array.When the compiler performs overload resolution on the version where you pass
nulldirectly into the function, it does not convert the parameter into an array sincenullis a valid value for this. However, when you pass in a null-valued object variable, overload resolution has to turn that into an object array. This means that you are passing an object array with one value, which isnull. The runtime then looks for a constructor with one argument, which it would then passnullto.This is why the resolution fails at runtime.