Search code examples
c#inherited

Get an instance for each class that implements an Interface


In order to solve a problem that I have in my solution using reflection, I need to specify the following code to show the user a CheckedListBox which exposes a list of conditions that they have to choose, and according with their choose it modifies a certain behavior in the application. At this time, I don't have problem to get the string name of the inherited classes thanks to this post, but I couldn't figure out how to get an instance of each one.

        DataTable table = new DataTable();
        table.Columns.Add("Intance", typeof(IConditions)); //INSTANCE of the inherited class
        table.Columns.Add("Description", typeof(string)); //name of the inherited class

        //list of all types that implement IConditions interface
        var interfaceName = typeof(IConditions);
        List<Type> inheritedTypes = (AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(s => s.GetTypes())
            .Where(p => interfaceName.IsAssignableFrom(p) && p != interfaceName)).ToList();

        foreach (Type type in inheritedTypes)
        {
            IConditions i; //here is where I don't know how to get the instance of the Type indicated by 'type' variable

            //I.E: IConditions I = new ConditionOlderThan20(); where 'ConditionOlderThan20' is a class which implements IConditions interface

            table.Rows.Add(i, type.Name);
        }

Is possible to get an object? What is the better approach to deal with problems like this?


Solution

  • Just use Activator.CreateInstance method:

    IConditions i = Activator.CreateInstance(type) as IConditions;
    

    Note: This will fail if type does not have parameterless constructor. You can use then version with parameters:

    public static Object CreateInstance(Type type, params Object[] args)