Alexander
Alexander

Reputation: 17

Using Collection<Interface> is possible, but does it correct?

The best practices are to program against the interface rather than the concrete class. I want to keep container of class that implements interface IPet. Does it correct? List<IPet> petList = new List<IPet>(); Or it's better to create an abstract class?

public interface IPet
    {
        string Name { get; set; }
        void Introduce();
    }
    public class Parrot : IPet
    {
        public string Name { get; set; }

        public Parrot(string name)
        {
            Name = name;
        }

    public void Introduce()
    {
        Console.WriteLine($"My name is {Name}. I am a parrot");
    }
}

public class Cat : IPet
{
    public string Name { get; set; }
    public Cat(string name)
    {
        Name = name;
    }

    public void Introduce()
    {
        Console.WriteLine($"My name is {Name}. I am a cat");
    }
}

  PetShop petShop = new PetShop();
  petShop.Add(new Cat("Garfield"));
  petShop.Add(new Parrot("Kesha"));

Upvotes: 0

Views: 42

Answers (2)

Andrey Polyakov
Andrey Polyakov

Reputation: 233

Using interface in generics is the good choice!

Using abstract class force you to place any type in single chain of inheritance that can cause a problem with application evolution.

Besides, if you have a repeating behavoir you can create abstract class wich implements required interface, so you'll get advantages of both ways.

Upvotes: 1

Filkolev
Filkolev

Reputation: 460

You can easily create an abstract class and put all repeating logic into it. Your classes look the same, only the Introduce() method is different, but you can use this.GetType().Name.ToLower() instead of "cat" and "parrot".

So, you can have the following:

public abstract class Pet : IPet
{
    public string Name { get; set; }

    protected Pet(string name)
    {
        Name = name;
    }

    public void Introduce()
    {
        Console.WriteLine($"My name is {Name}. I am a {this.GetType().Name.ToLower()}");
    }
}

public class Cat : Pet
{    
    public Cat(string name)
        : base(name)
    {       
    }   
}

Upvotes: 0

Related Questions