Shad
Shad

Reputation: 1219

Inheritance guideline for a child class

Since in C#, we can only inherit from a single base class and implement multiple interfaces.

I see this normal pattern everywhere:-

DerivedClass : BaseClass, IInterface1, IInterface2

How should one decide what goes inside BaseClass and what things inside the interfaces?

Are there any guidelines for it?

Upvotes: 0

Views: 64

Answers (2)

devcrp
devcrp

Reputation: 1348

I use to follow these rules:

  1. Base classes contain common methods or properties that will be used by its children, this is mainly to avoid having duplicated code in each child class.
  2. Interfaces contain the methods or properties that need to be used outside the context of those classes. And depending on the case they will be implemented by the base class or by the child classes.

So it can happen that you want to have a method or property in the base class AND in the interface, and sometimes you will want it to be only in the base class because it's only a utility for its children.

But like everything in design, there're no 100% correct answers, it really depends on the context and the meaning of each object.

Upvotes: 2

Implementations should go into the base class while declarations into the interfaces. There can be some exceptions e.g. if a declaration is strongly coupled with an implementation, then both can go into base class. ( with C# 8 interfaces can have default implementations, but this should not be misused in my opinion)

Upvotes: 1

Related Questions