Search code examples
c#.netreflection.net-assemblyactivator

Can I use Activator.CreateInstance with an Interface?


I have an example:

        Assembly asm = Assembly.Load("ClassLibrary1");
        Type ob = asm.GetType("ClassLibrary1.UserControl1");
        UserControl uc = (UserControl)Activator.CreateInstance(ob);
        grd.Children.Add(uc);

There I'm creating an instance of a class, but how can I create an instance of a class which implements some interface? i.e. UserControl1 implements ILoad interface.

U: I can cast object to interface later, but I don't know which type in the assemblies implements the interface.


Solution

  • This is some code i have used a few times. It finds all types in an assembly that implement a certain interface:

    Type[] iLoadTypes = (from t in Assembly.Load("ClassLibrary1").GetExportedTypes()
                         where !t.IsInterface && !t.IsAbstract
                         where typeof(ILoad).IsAssignableFrom(t)
                         select t).ToArray();
    

    Then you have all types in ClassLibrary1 that implement ILoad.

    You could then instantiate all of them:

    ILoad[] instantiatedTypes = 
        iLoadTypes.Select(t => (ILoad)Activator.CreateInstance(t)).ToArray();