Is there a way to automatically cast an object to a specific type when passing that object into an overloaded method?
I have three classes that all inherit from a base class
class Cat : Animal
class Dog : Animal
class Tiger : Animal
I have another class, a class that writes to a database (dbInterface)
that has an overloaded create method for each of these types
void Create(Cat cat);
void Create(Dog dog);
void Create(Tiger tiger);
I would like to call a Create method like so
Animal cat = new Cat();
dbInterface.Create(cat);
and I'd like this to call the Create(Cat cat)
method specifically. Currently this doesn't happen because cat is type Animal.
Currently what I'm doing that I don't particularly like is I have a generic create method Create(Animal animal)
and in that method I check for a valid cast and call the appropriate method.
void Create(Animal animal)
{
Cat cat = animal as Cat;
if (cat != null)
{
Create(cat);
}
... for Dog and Tiger too ...
}
Is there a better way to do this or am I doing something stupid?