When To Use Abstract Class/Methods Instead Of Normal Class/Methods In C#

Abstract class basically allows us to provide default functionality for all the child classes through non-abstract methods.
 
Below are reasons to define a class as abstract,
  1. When we do not want developers to create object of parent class because parent class object won't allow us to use method of child class, and will probably give run time exception if any method throws MethodNotImplemented exception in base class. So use abstract class instead of concrete class.And when we try to create object of an abstract class user will get error on compilation instead of run-time. So,it is safe to have abstract class.

  2. Updating base class in large project system is easier than changing it in interface. In case we have added one new parameter to non-abstract method of abstract class then we only need to update the calling part where we need to pass an extra parameter. But changing this in interface will break the code in all the inherited classes of the interface where actual implementation is written. 

  3. Code duplicacy/maintainability needs to be handled by reusing the code. And abstract helps that part.
Why do we need abstract method in abstract class?

When we want to force child class to provide the implementation of any method.
 
Suppose we have child classes for full-time and part-time employees and they needed to calculate salary of both type of employees separately since they have different implementation for the calculations. A full timer may be on a yearly basis and part timers are on a monthly or project basis. In that case we need to have an abstract method called calculateSalary() in abstract class and why we need it is because we must require the salary of each employee irrespective of its type, otherwise child classes may neglect it to give it an implementaion. Since it's in abstract class, compiler will make sure that each child class has its own separate implementation.
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now