jeudi 2 mars 2023

How to implement in C# class generic method or template to prevent dynamic casting

I have a question about implementation without dynamic casting.

In order to demonstrate my problem here is a toy problem, in C#:

public abstract class Animal
{
    protected bool ate = false;
    public abstract void Speak();
    public void Eat()
    {
        this.ate = true;
    }
}
public class Dog : Animal
{
    public override void Speak()
    {
        Console.WriteLine("Woof");
    }
}
public class Cat : Animal
{
    public override void Speak()
    {
        Console.WriteLine("Meow");
    }
}

public class DataBase
{
    public List<Dog> dogs_list = new List<Dog>();
    public List<Cat> cats_list = new List<Cat>();
    public void AddAndFeed(Animal animal)
    {
        animal.Eat();
        this.Add(animal);
    }
}

public void Main()
{
    Dog dog = new Dog();
    Cat cat = new Cat();
    Database database = new Database();
    d.Add(dog);
    d.Add(cat);
}

the Add function should get Animal as input because I want to simplify the interface: the user should not care if the specific instance is a Cat or a Dog (but it is always derived from class Animal). How can I implement the Add function for Database properly without dynamic casting and without code duplication?

I tried using dynamic casting for example:

public void Add(Animal animal)
{
    if (animal is Dog)
        dogs_list.Add(animal as Dog);
    else if (animal is Cat)
        cats_list.Add(animal as Cat);
}

And also I tries code duplication using overloading function but I doesn't fit the design pattern:

public void Add(Dog dog) {...}
public void Add(Cat cat) {...}

Aucun commentaire:

Enregistrer un commentaire