Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 499
Arman Hayots Avatar asked May 24 '12 07:05

Arman Hayots


People also ask

What does activator CreateInstance do?

The Activator. CreateInstance method creates an instance of a type defined in an assembly by invoking the constructor that best matches the specified arguments. If no arguments are specified then the constructor that takes no parameters, that is, the default constructor, is invoked.

What is activator CreateInstance in net core?

CreateInstance(ActivationContext, String[]) Creates an instance of the type that is designated by the specified ActivationContext object and activated with the specified custom activation data. CreateInstance(Type) Creates an instance of the specified type using that type's parameterless constructor.

Can you make an instance of an interface?

You cannot create an instance of an interface , because an interface is basically an abstract class without the restriction against multiple inheritance. And an abstract class is missing parts of its implementation, or is explicitly marked as abstract to prohibit instantiation.

Can not create an instance of the abstract class or interface?

No, you cannot create an instance of an abstract class because it does not have a complete implementation. The purpose of an abstract class is to function as a base for subclasses. It acts like a template, or an empty or partially empty structure, you should extend it and build on it before you can use it.


1 Answers

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();
like image 110
Botz3000 Avatar answered Oct 13 '22 13:10

Botz3000