Search code examples
c#objectreflectionmissingmethodexception

MissingMethodException when creating an object with reflection


I'm using reflection to create objects coming from an external assembly. My problem is that I cannot create an object that way:

Type t = assembly.GetType("ExternalClass");
object obj = Activator.CreateInstance(t, new object[] { data, Type.Missing, Type.Missing });

I get System.MissingMethodException: Additional information: Constructor on type 'ExternalClass' not found. However everything works fine using that way:

Type t = assembly.GetType("ExternalClass");
ConstructorInfo[] constructors = t.GetConstructors();
object obj = constructors[0].Invoke(new object[] { data, Type.Missing, Type.Missing });

ExternalClass has only 1 constructor with 2 optional parameters and I'm sure I'm passing correct arguments, because the second way creates the object I want. Do I miss something in the first approach? I would prefer the first one, because it's easier to read

EDIT: I forgot about CultureInfo (why would this method need it?!). The solution is to use:

object obj = Activator.CreateInstance(t,
    BindingFlags.CreateInstance |
    BindingFlags.Public |
    BindingFlags.Instance |
    BindingFlags.OptionalParamBinding, null, new object[] { data, Type.Missing, Type.Missing }, CultureInfo.CurrentCulture);

Solution

  • This is the way how you should construct the constructor with the Activator

    (T)Activator.CreateInstance(typeof(T), 
        BindingFlags.CreateInstance |
        BindingFlags.Public |
        BindingFlags.Instance |
        BindingFlags.OptionalParamBinding, null, new object[] { data, Type.Missing, Type.Missing }, CultureInfo.CurrentCulture);