c# Abstract Class implementing an Interface

I've seen the following code layout reading forums and other blog posts and adapted in order to ask a few questions.

public interface IService<T>
    int Add(T entity);
    void Update(T entity);

public abstract class ServiceBase<T> : IService<T>
    public int Add(T entity) { ... }
    public void Update(T entity) { ... }

public interface ICarService : IService<Car>

public class SomeBaseClass : ServiceBase<Car>, ICarService
    public int Add(Car entity);
    public void Update(Car entity);

What I don't understand is the benefit of having the abstract class implmenting the interface. To me it just feels a bit repetitive and I cannot understand the benefit of having an abstract class implementing the interface.

  1. Why doesn't the abstract class ServiceBase<T> just define as is without the need to inherit the IService interface? Is this doubling up the code?
  2. Why must the SomeBaseClass also implment the ICarService? Shouldn't the ServiceBase be sufficient?

1 Answer

  1. Patrick- Reply


    Ad 1: The additional abstract base class allows you to evolve the interface without breaking the implementation. Supposed there was no abstract base class, and you'd extend the interface, let's say by adding a new method. Then your implementation was broken, because your class does not implement the interface any longer.

    Using an additional abstract base class you can separate this: If you add a new method to the interface, you can provide a virtual implementation in the base class and all your sub-classes can stay the same, and can be adopted to match the new interface at a later point in time.

    Moreover, this combination allows you to define a contract (using the interface) and provide some default mechanisms (using the abstract base class). Anyone who's fine with the defaults can inherit from the abstract base class. Anyone who wants super-duper fine control about any little detail can implement the interface manually.

    Ad 2: From a technical point of view there is no NEED to implement the interface in the final class. But this, again, allows you to evolve things separately from each other. A CarService is for sure a Service<Car>, but maybe it's even more. Maybe only a CarService needs some additional stuff that should not go into the common interface nor into the service base class.

    I guess that's why ;-)

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>