AngryHacker
AngryHacker

Reputation: 61606

How to instantiate a specific subtype from param array?

Consider the following code:

public abstract class BaseClass {
    abstract void DoWork();
    virtual void MoreWork() {
        Console.WriteLine("MoreWork");
    }
}
public class classA : BaseClass {
    public void DoWork() { DoStuffA(); }
}
public class classB : BaseClass {
    public void DoWork() { DoStuffB(); }
}

I want to have a method to which I'd like to pass all these types and have them be instantiated.

void Initialize(params BaseClass[] lst) {
    for (int i = 0; i < objectList.Length; i++) {
       Activator.CreateInstance(objectList[i]); // not sure if this works.
    }
}

Initialize(classA, classB);

How do I pull off something like that?

Upvotes: 0

Views: 70

Answers (1)

Jeroen van Langen
Jeroen van Langen

Reputation: 22038

You should not send object instances to the initialize method, but their types.

void Initialize(params Type[] lst) {
    foreach(Type type in lst) {
       Activator.CreateInstance(type);
    }
}

Initialize(typeof(classA), typeof(classB));

Here is a complete example:

    public Form1()
    {
        InitializeComponent();

        Initialize(typeof(ClassA), typeof(ClassB));
    }

    public class BaseClass { }

    public class ClassA : BaseClass { }

    public class ClassB : BaseClass { }

    public BaseClass[] Initialize(params Type[] lst)
    {
        // if we already know the item count, why not set the capacity of the list.
        List<BaseClass> instances = new List<BaseClass>(lst.Length);

        foreach (Type type in lst)
            if (type.IsSubclassOf(typeof(BaseClass)))
                instances.Add((BaseClass)Activator.CreateInstance(type));

        return instances.ToArray();
    }

Upvotes: 2

Related Questions