Search code examples
c#listinheritanceactivator

C# - Create a derived class instance from string then add to base class list


I'll be reading a string input that will determine what type of derived class to create. The object created then gets added to a list of baseclass objects.

When trying to add the the result of Activator.CreateInstance(); to the list I get:

Cannot implicitly convert type 'object' to 'Namespace.Animal'. An explicit conversion exists (are you missing a cast?)

I've gotten the below:

List<Animal> animals;

Type animal_type = Type.GetType(class_name); // eg lion, tiger
object new_animal = Activator.CreateInstance(animal_type);

animals.Add(new_animal);

How can I add the newly created object to the list?


Solution

  • As the error says, you need an explicit cast:

    animals.Add( (Animal) new_animal);
    

    new_animal is of type object. So, new_animal could be just about anything. The compiler needs you to explicitly tell it to take the dangerous step of assuming it's of type Animal. It will not make that assumption on its own because it cannot guarantee the conversion will work.