Question

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?

Was it helpful?

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.

OTHER TIPS

Cast the result from Activator.CreateInstance to Animal:

List<Animal> animals;

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

animals.Add(new_animal);

To extend on the other answers you need to cast to Animal first. However if you are not 100% sure that you will be getting a class derived from Animal every time here is a better way to check.

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

Animal new_animal = new_object as Animal; //Returns null if the object is not a type of Animal

if(new_animal != null)
    animals.Add(new_animal);

The other answers will throw an exception if the type you passed in to class_name was not a type of Animal, this method will just not add it to the list and continue on.

The way you are doing it is Implicit casting. you should cast Explicitly instead. Try:

object new_animal = (Animal) Activator.CreateInstance(animal_type);

As other have said, you need to cast your Object to Animal. But you probably should check to be sure the type you are creating is assignable to Animal before instantiating your object.

  public bool AddNewAnimal(List<Animal> animals, string className)
  {
     bool success = false;

     Type animalType = Type.GetType(className);
     if (typeof(Animal).IsAssignableFrom(animalType))
     {
        object newAnimal = Activator.CreateInstance(animalType);
        animals.Add((Animal)newAnimal);
        success = true;
     }

     return success;
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top