Use an Abstract Class in C#

Question: Why and when should we use an abstract class? Provide an example of where we could use an abstract class.

Answer


Let's understand with an example. In an organization there are two types of employees FullTimeEmployee and contractEmployee.

For the first we will create a FullTimeEmployee class in a console application and provide the implementation of the class with the following procedure.

Step 1

Create a console application and name it InterviewQuestionPart3.

console application

Step 2

Add a class file to the console application and provide it the name FullTimeEmployee.

add new class

class

Step 3

Provide the implementation for the class with the following code.

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Text;    
  5.     
  6. namespace InterviewQuestionPart3    
  7. {    
  8.     class FullTimeEmployee    
  9.     {    
  10.         public int ID { getset;}    
  11.         public string FirstName { getset; }    
  12.         public string LastName { getset; }    
  13.         public int AnnualSalary { getset; }    
  14.            
  15.         public string GetFullName()    
  16.         {    
  17.             return this.FirstName + " " + LastName;    
  18.         }    
  19.     
  20.         public int GetMonthlySalary()    
  21.         {    
  22.             return this.AnnualSalary/12;    
  23.         }    
  24.     }    
  25. }  
Step 4
 
Now create another employee, add another class file to the console application and provide the name contractEmployee.

Add a another class

Step 5
 
Provide the implementation for the class with the following code:
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Text;    
  5.     
  6. namespace InterviewQuestionPart3    
  7. {    
  8.      public class ContractEmployee    
  9.     {    
  10.     
  11.         public int ID { getset; }    
  12.         public string FirstName { getset; }    
  13.         public string LastName { getset; }    
  14.         public int HourlyPay { getset; }    
  15.         public int TotalHours { getset; }    
  16.     
  17.     
  18.         public string GetFullName()    
  19.         {    
  20.             return this.FirstName + " " + LastName;    
  21.         }    
  22.     
  23.         public int GetMonthlySalary()    
  24.         {    
  25.             return this.TotalHours * this.HourlyPay;    
  26.         }    
  27.     }    
  28. }  
Step 6
 
Now if we need to use this classes in the programe.cs file, we have a Main method to create an instance of the FullTimeEmployee class and contractEmployee class and define several properties using the following code.
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Text;    
  5.     
  6. namespace InterviewQuestionPart3    
  7. {    
  8.     class Program    
  9.     {    
  10.         static void Main(string[] args)    
  11.         {    
  12.             FullTimeEmployee fte = new FullTimeEmployee();    
  13.             {    
  14.                 fte.ID = 101;    
  15.                 fte.FirstName="shaili";    
  16.                 fte.LastName = "dashora";    
  17.                 fte.AnnualSalary=60000;    
  18.     
  19.             };    
  20.             Console.WriteLine(fte.GetFullName());    
  21.             Console.WriteLine(fte.GetMonthlySalary());    
  22.             Console.WriteLine("--------------");    
  23.     
  24.     
  25.     
  26.             ContractEmployee cte = new ContractEmployee();    
  27.             {    
  28.                 cte.ID = 101;    
  29.                 cte.FirstName = "sourabh";    
  30.                 cte.LastName = "somani";    
  31.                 cte.HourlyPay = 200;    
  32.                 cte.TotalHours = 40;    
  33.     
  34.             };    
  35.             Console.WriteLine(cte.GetFullName());    
  36.             Console.WriteLine(cte.GetMonthlySalary());    
  37.                 
  38.         }    
  39.     
  40.      }    
  41.  }  
Step 7
 
Now see the output. The FullTimeEmployee full name is Shaili Dashora and the monthly salary is 5000 and the contractEmployee full name is Sourabh Somani and the monthly salary is 8000.

output

It is working fine as our expected output.

But the problem is that in this design, we see in these classes that both have a type of employee, some properties are also the same in both classes like employee ID, FirstName, LastName and the GetfullName method are all the same in both. The only difference is that here FullTimeEmployee has an Annual Salary and ContractEmployee has some more properties like hourly pay and total hours worked. That is the silly difference between both of the classes otherwise they are nearly similar.

employee class code

So we have a lot of duplicated code here and code maintainability will be a problem because if we want to add a MiddleName property then we need to do that for both of the classes, whether you are a FullTimeEmployee or ContractEmployee you may have a middle name.

And in order to compute a fullName we need to introduce again the MiddleName in both of the classes. Here we have only two related classes but in reality depending on the types of objects that we are creating, we have several related classes.

Suppose in this example we have a part-time employee, a director employee or things like that so if we have more related classes then the number of places that we need to make changes will grow as well and that is vulnerable to error or is time consuming so code maintainability will be a big issue if we duplicate the code like this. So how to solve this problem?

Here two classes are related and some common functionality between them or some duplicate functionality exists between them, so to solve this problem we can move the common functionality from both of the classes into a base class and then we can inherit these two class from the base class.

But if we have design a base class for these two classes then the following two questions arise: 
  • Should we design it as an abstract class?
  • Should we design it as a concrete (non-abstract) class?

Step 8

First let's design it as a concrete class and see what the problems that we encounter are.

Now we will add another class named BaseEmployee.

In this BaseEmployee class we will move the common properties from the FullTimeEmployee class like the ID, FirstName, LastName and GetFullName methods, these are common in both classes.

FullTimeEmployee cs

Now we will make the FullTimeEmployee class as inherited from the BaseEmployee class. So it has all the properties of the base class like the following code.

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Text;    
  5.     
  6. namespace InterviewQuestionPart3    
  7. {    
  8.     class FullTimeEmployee:BaseEmployeeClass    
  9.     {    
  10.         public int AnnualSalary { getset; }    
  11.         public int GetMonthlySalary()    
  12.         {    
  13.             return this.AnnualSalary/12;    
  14.         }    
  15.     }    
  16. }   
In a similar way we will make a ContractEmployee class that is also inherited from the BaseEmployee class and removes all the common properties that already exist in the base class.

base employee class

Now the ContractEmployee class code will be like this:
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Text;    
  5.     
  6. namespace InterviewQuestionPart3    
  7. {    
  8.      public class ContractEmployee:BaseEmployeeClass    
  9.     {    
  10.         public int HourlyPay { getset; }    
  11.         public int TotalHours { getset; }    
  12.     
  13.         public int GetMonthlySalary()    
  14.         {    
  15.             return this.TotalHours * this.HourlyPay;    
  16.         }    
  17.     }    
  18. }  
Step 9
 
Now in the BaseEmployee class we introduce one more method, GetMonthlySalary, and marked as virtual because the BaseEmploee class does not know how to provide the implementation for ContractEmployee or FullTime Employee. It is the responsibility of the derived classes to do that, thats why we marked it as virtual. And throw a NotImplementedException. Like the following code:
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Text;    
  5.     
  6. namespace InterviewQuestionPart3    
  7. {    
  8.     public class BaseEmployeeClass    
  9.     {    
  10.         public int ID { getset; }    
  11.         public string FirstName { getset; }    
  12.         public string LastName { getset; }    
  13.     
  14.         public string GetFullName()    
  15.         {    
  16.             return this.FirstName + " " + LastName;    
  17.         }    
  18.     
  19.          public virtual int GetMonthlySalary()    
  20.         {    
  21.             throw new NotImplementedException();    
  22.         }    
  23.     
  24.              
  25.     }    
  26. }  
Now in the derived classes we override the GetMonthlySalary method and provide the implementation of that specific class.

Now when we build the program we get the same output like this.

program output

So here what we did is we moved all the common code in BaseEmployeeClass so if we want to introduce the middle name property we include it only within the Base class and it will be available for all the derived classes so code maintainability will be much easier.

So by introducing the non-abstract (concrete) class then we need to encounter the other problem that in our organization we have only two types of employees, FullTimeEmployee and ContractEmployee so in the Main method we are creating an instance of these employee classes and using them the way we want to.

Now the BaseEmployeeClass is the concrete class so we can create the instance of the BaseEmployeeClass and initialize the properties and access the methods then we build the program we did not get any compile time error.

build program

But when we run this it will throw a run time exception because when we look at the BaseEmployeeClass GetMonthlySalary method. Here this class doesn't know the implementation of the method and throws a NotImplementedException when we run the program.

BaseEmployeeClass

Step 10
 
That is one problem. Another problem is that in this concept of our organization we have only two types of employees FullTimeEmployee and ContractEmployee and they are nothing like BaseEmployee, it is only an abstract concept since we want the common functionality present to be in the base class. We moved the functionality into the BaseEmployeeClass but there is no BaseEmployee in our organization, so we don't want developers to create the instance of the BaseEmployeeClass. Using it like this, we want to prevent them from doing this, since we create class as non-abstract that is a concrete class so we are unable to stop the developers from doing this, that is the problem with using the non-abstract class here.

Now at the runtime we simply achieve the solution of this problem to remove the virtual method GetMonthlySalary from BaseEmployeeClass and remove the override keyword from the methods to the respected class like FullTimeEmployeeClass and ContractEmployeeClass.

BaseEmployeeClass cs code

And at the Main method we cannot invoke the GetMonthsalary Method so we remove the invocation.

get month selary method

Now we run the program and get the expected output like this:

cmd output

But we still have the problem that we don't want the developers to create an instance of the BaseEmployee class since we do not have that type of employee. Here we want to prevent developers from doiing that. So for this we need to simply mark BaseEmployeeClass as Abstract like this.
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Text;    
  5.     
  6. namespace InterviewQuestionPart3    
  7. {    
  8.     public abstract class BaseEmployeeClass    
  9.     {    
  10.         public int ID { getset; }    
  11.         public string FirstName { getset; }    
  12.         public string LastName { getset; }    
  13.     
  14.         public string GetFullName()    
  15.         {    
  16.             return this.FirstName + " " + LastName;    
  17.         }    
  18.      }    
  19. }  
Now at the Main method we have a compile time error like this:

compile time error

So this is the advantage of creating a class as abstract, it prevents the accidental creation of an instance of the BaseEmployeeClass.

We cannot even compile them, we instead get the following compiler error.

get compiler error

Now we will comment out the instance of the BaseClassEmployee, then run it again and get good output.

comment the instance

Step 11
 
Now for some modifications that we will make to the BaseEmployeeClass. We will introduce the GetMonthlySalary method to this class and make it an abstract method so if we make the method as abstract then we do not need to provide the implementation, only a declaration and at the derived classes we will provide the implementation by overriding it.
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Text;    
  5.     
  6. namespace InterviewQuestionPart3    
  7. {    
  8.     public abstract class BaseEmployeeClass    
  9.     {    
  10.         public int ID { getset; }    
  11.         public string FirstName { getset; }    
  12.         public string LastName { getset; }    
  13.     
  14.         public string GetFullName()    
  15.         {    
  16.             return this.FirstName + " " + LastName;    
  17.         }    
  18.     
  19.         public abstract int GetMonthlySalary();    
  20.     
  21.              
  22.     }    
  23. }   
The following is the code for ContractEmployeeClass.
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Text;    
  5.     
  6. namespace InterviewQuestionPart3    
  7. {    
  8.      public class ContractEmployee:BaseEmployeeClass    
  9.     {    
  10.         public int HourlyPay { getset; }    
  11.         public int TotalHours { getset; }    
  12.     
  13.         public override int GetMonthlySalary()    
  14.         {    
  15.             return this.TotalHours * this.HourlyPay;    
  16.         }    
  17.     }    
  18. }   
The following is the code for FullTimeEmployeeClass. 
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Text;    
  5.     
  6. namespace InterviewQuestionPart3    
  7. {    
  8.     class FullTimeEmployee:BaseEmployeeClass    
  9.     {    
  10.         public int AnnualSalary { getset; }    
  11.         public override int GetMonthlySalary()    
  12.         {    
  13.             return this.AnnualSalary/12;    
  14.         }    
  15.     }    
  16. }    
Now we see the output is the same as the previous.

output same as previous

The reason we introduced the abstract method in the BaseEmployee class is to force all the derived classes to provide the implementation of the GetMonthlySalary abstract method. Otherwise we get a compilation error if we do not provide the implementation of the method in the derived classes, like this.

contractEmployee classes

And it is good thing because we have a different type of employee and they have a different Monthly Salary. The abstract method forces us to provide the implementation in the derived classes.

abstract class

Conclusion

So in this case we moved the common functionality from the FullTimeEmployee and contractEmployee classes into the BaseEmployeeClass and made it an abstract class because we don't want developers to accidentally create an instances of the abstract BaseEmployeeClass.

Now if our requirement is such that we want to instantiate the Base class then we need to use normal inheritance and not mark the class as an abstract class.

So it is a base class and two derived classes.

a base class and two derived classes

 


Similar Articles