The title may be unclear, but please look at the pattern below
public abstract class Animal
{
public abstract Dog GetDog { get; }
public abstract Cat GetCat { get; }
}
public class Dog : Animal
{
public override Dog GetDog {
get { return this; }
}
public override Cat GetCat {
get { return null; }
}
}
Is this considered a bad practice to have properties in the base class, return derived types. Or should I do something like
public abstract AnimalTypeEnum AnimalType { get; }
EDIT: Based on the comments, I guess I should be more clear on what I am trying to achieve. A new instance of the Dog or Cat class would be created by a separate function based on certain criteria and would then return Animal type to the caller. The calling method would check the type of the returned instance and use it accordingly.
public Animal CreateAnimal(string path)
{
//Process the document in path and create either a new instance of dog or cat
Dog dg = new Dog();
return dg;
}
There’s your problem. It’s code smell to need to do that. You should be able to treat whatever it is as just an object, rather than treating dogs and cats differently.
If you need to display the content of either animal, then override the
ToStringmethod on both classes and just callToStringon animal. If you need to know the name of the dog or cat then add aNameproperty toAnimal. If at all possible you should be using polymorphism here so that whatever is using the object treads it as just anAnimaland simply involves different things happening as a result of different implementations of the same method.If you really, really do need to know whether the
Animalis aDogor aCatthen you can use theisorasoperators; you don’t need to add all of the code that you’ve shown in the OP.