Instantiating a constructor with parameters in an internal class with reflection

The issue is that Activator.CreateInstance(Type, object[]) does not consider non-public constructors.

Exceptions

MissingMethodException: No matching
public constructor was found.

This is easily shown by changing the constructor to publicvisibility; the code then works correctly.

Here’s one workaround (tested):

 BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance;
 CultureInfo culture = null; // use InvariantCulture or other if you prefer
 object instantiatedType =   
   Activator.CreateInstance(typeToInstantiate, flags, null, parameter, culture);

If you only require the parameterless constructor this will work as well:

//using the overload: public static object CreateInstance(Type type, bool nonPublic)
object instantiatedType = Activator.CreateInstance(typeToInstantiate, true)

Leave a Comment