Mohe TheDreamy
Mohe TheDreamy

Reputation: 387

Create new instance of a certain type dynamically

I have this parent class "Component", and some classes inherited from it "Component1", "Component2".. etc

I have a list List<Component> Components and I need to create new instances of some classes that are inherited from it and add them to the list Components

The way I am doing it now is something like

private void AddComponent(string componentType)
{
    if (componentType == "component1")
    {
        Components.Add(new component1());
    }
    if (componentType == "component2")
    {
        Components.Add(new component2());
    }
    // and so on
}

As my code gets larger, I need to add more components. So I wonder if there is a better way to go about things.

I looked around and found this way which didn't work for me:

    var newComponent = Activator.CreateInstance(Type.GetType(componentType));
    newComponent = Convert.ChangeType(newComponent, Type.GetType(componentType));

    Components.Add(newComponent);

it says: cannot convert from 'object' to Component

EDIT: Solved, I forgot to do casting.

Upvotes: 0

Views: 68

Answers (2)

Enigmativity
Enigmativity

Reputation: 117019

You should just be able to do this:

var newComponent = Activator.CreateInstance(Type.GetType(componentType));
Components.Add((Component)newComponent);

Activator.CreateInstance will simply create the object - there is no need to convert it to anything else. Just a simple cast will let you add it to your list.

Upvotes: 1

Brandon Gano
Brandon Gano

Reputation: 6710

If the derived classes have empty constructors and you're okay using the component type directly instead of passing a string representation, you could do something like this:

private void AddComponent<T>() where T : Component, new()
{
  Components.Add(new T());
}

/* ... */

AddComponent<Component1>();
AddComponent<Component2>();

This assumes Component is the base class from which all other components derive.

Upvotes: 4

Related Questions