I have a public class with 2 constructors: The default (without parameters), which is internal, and a different one, which is public. The default constructor calls the other one with some default values.
I call the internal constructor using reflection, so it's not used anywhere in the assembly statically (only by reflection).
When I make the reflection call, I'm getting:
System.MissingMethodException
Message=No parameterless constructor defined for this object.
I know of two workarounds:
Any better solutions to this problem?
It's worth mentioning that if the default constructor is public, I don't get that exception.
Thanks,
Boaz.
The constructor is not removed, probably in the search of your constructor you should specify the flag BindingFlag.NonPublic
.
class xxx
{
private xxx() :
this(10)
{
}
public xxx(int value)
{
Console.WriteLine(value);
}
}
static void Main(string[] args)
{
Activator.CreateInstance(typeof(xxx), true);
Console.ReadLine();
}
Activator.CreateInstance have an overload with a boolean where you can specify if you want to call a non public constructor.
public static Object CreateInstance(
Type type,
bool nonPublic
)
Activator.CreateInstance(type, true) will call the constructor both if it is public or private\internal\protected.