Search code examples
c#interfacepolymorphismsupertype

Is it better to code to SuperType or Interface?


What is considered general best practice:

Reference via the super type?

public class BirdFeeder{

    public Feed(Bird bird){...}

}

Or via a Interface

public class BirdFeeder{

    public Feed(IBird iBird){...}

}

Personally I prefer interfaces but I'm not quite sure why, to me they just feel 'cleaner'. I would like a better understanding of why I would choose one over another.

Thanks


Solution

  • You are correct about the interfaces, they offer you more flexibility in designing your inheritance hierarchy.

    Suppose that you have a hierarchy that starts with a base class Bird, and continues down to various species of birds. Now suppose that you would like to add a mechanical bird to the hierarchy of birds, but you would rather derive it from the Robot base class. If your feeder takes Bird arguments, your mechanical bird would need a special feeder. If the feeder take an IBird, however, there would be no problem sending a RoboBird to it, as long as it implements the IBird interface correctly.