Search code examples
c#reflectioncompact-framework

Compact Framework - how do I dynamically create type with no default constructor?


I'm using the .NET CF 3.5. The type I want to create does not have a default constructor so I want to pass a string to an overloaded constructor. How do I do this?

Code:

Assembly a = Assembly.LoadFrom("my.dll");
Type t = a.GetType("type info here");
// All ok so far, assembly loads and I can get my type

string s = "Pass me to the constructor of Type t";
MyObj o = Activator.CreateInstance(t); // throws MissMethodException

Solution

  • MyObj o = null;
    Assembly a = Assembly.LoadFrom("my.dll");
    Type t = a.GetType("type info here");
    
    ConstructorInfo ctor = t.GetConstructor(new Type[] { typeof(string) });
    if(ctor != null)
       o = ctor.Invoke(new object[] { s });