Is it possible to create a derived class from a base class constructor?

c#, inheritance, polymorphism

Solution

What you are looking for is either a 'virtual constructor' (not possibe in C#) or the Factory pattern.

class Animal
{
   // Factory method
   public static Animal Create(string name)
   {
      Animal animal = null;
      ...  // some logic based on 'name'
          animal = new Zebra();

      return animal;
   }
}

The Factory method can also be placed in another (Factory) class. That gives better decoupling etc.

Problem

I have say 3 classes, Animal, Cat & Dog. ``` // calling code var x = new Animal("Rex"); // would like this to return a dog type var x = new Animal("Mittens"); // would like this to return a cat type if(x.GetType() == typeof(Dog)) { x.Bark(); } else { x.Meow(); } class Animal { public Animal(string name) { // check against some list of dog names ... find rex // return Animal of type Dog. // if not... // check against some list of cat names ... find mittens // return Animal of type Cat. } } ``` Is this possible somehow? If not is there something similar I can do?

Original source