Inheritance in C#

Inheritance in C#

In simple word, we can define inheritance means to take something that is already made (or available).

Inheritance is one of the most important features of object-oriented programming which is used in real-time. It is the concept which is used for code reusability and changeability purpose.

Here changeability means overriding the existed functionality or feature of the object or adding more functionality to the object.

What is inheritance?

The process of creating a new class from an existing class such that the new class acquires all the properties and behaviors of the existing class is called as inheritance.

In other words, we can also say that the process of inheriting the properties and behaviors from one class to another class is called as inheritance.

The properties (or behaviors) are transferred from which class is called as the superclass or parent class or base class.

The class which derives the properties or behaviors from the superclass is known as subclass or child class or derived class.

In the inheritance process, the child class will get all the features of the parent/base class.

What are the advantages of inheritance?

The advantages of inheritance are code reusability and code changeability.

Classification of inheritance supported by C#.NET

C#.NET classified the inheritance into two categories, such as

  1. Implementation inheritance.
  2. Interface inheritance
Implementation inheritance:

This is the commonly used inheritance. Whenever a class is derived from another class then it is known as implementation inheritance.

Interface inheritance:

This type of inheritance is taken from Java. Whenever a class is derived from an interface then it is known as interface inheritance.

Types of inheritance in C#.net

Inheritance can be classified into 5 types.

  1. Single Inheritance
  2. Hierarchical Inheritance
  3. Multilevel Inheritance
  4. Hybrid Inheritance
  5. Multiple Inheritance
Single Inheritance

When a class is derived from a single base class then the inheritance is called as single inheritance.

Hierarchical Inheritance

Hierarchical inheritance is the inheritance where more than one derived classes are created from a single base class.

Multilevel Inheritance

When a derived class is created from another derived class, then that type of inheritance is called as multilevel inheritance.

Hybrid Inheritance

Hybrid Inheritance is the inheritance which is the combination of any single, hierarchical and multilevel inheritances.

Multiple Inheritance:

When a derived class is created from more than one base class then such type of inheritance is called as multiple inheritance. But multiple inheritance is not supported by .net using classes and can be done using interfaces.

Handling the complexity that causes due to the multiple inheritance is very complex. Hence it was not supported in dot net with class and it can be done with interfaces.

Rules to be considered while working with inheritance
Rule1:

In inheritance, the constructor of parent class must be accessible to its child class otherwise the inheritance will not possible because when we create the child class object first it goes and calls the parent class constructor so that the parent class variable will be initialized and we can consume them under the child class.

NOTE: The reason why a child class internally call its parent class constructor is to initialize parent class and can consume them under child class.

Rule2:

In inheritance, the child classes can consume the parent class members but parent class does not consume child class members that are purely defined in the child class.

Rule3:

Just like the object of a class can be assigned to a variable of same class to make it as a reference, it can also be assigned a variable of its parent to make it as reference so that the reference starts consuming memory of object assigned to it, but now also using that we control access child class pure members.

NOTE: A parent class object can never be assigned to a child class variable. A parent class reference i.e. created by using child class object can be converted back into a child class reference if required by performing an explicit conversion.

Situations where to implement inheritance:
  1. Assume that a company has n no of branches and asked to computerize branches details of the company, then we create a class like…

Class Branch having the data member (Data fields or variables) BranchCode, BranchName and BranchAddress and also methods (functions) like GetBranchData() and DisplayBranchData().

  1. Later after some period of time, the company also asked to computerize employee details of each branch. Then we create a class like…

Class Employee having the data member EmployeeId, EmployeeName, EmployeeAddress, EmployeeAge and also methods like GetEmployeeData() and DisplayEmployeeData().

  1. If we create two classes without inheritance we need to create the object for every class individually like below

Inheritance in C#

Here Obj1 is the object of Class Branch class and Obj2 is the object of Class Employee. So it becomes very difficult to identify which employee belongs to which branch and integrate the Branch class object with Employee class object.

So if we derive the Employee class from Branch class we create the object to the derived class Employee then it will represent both classes and will maintain the reference to the members of both base and derived classes like.

Inheritance in C#

Not it’s time to implement inheritance with an example. So let’s start coding.
namespace InheritanceDemo
{
    class Branch
    {
        int BranchCode;
        string BranchName, BranchAddress;
        public void GetBranchData()
        {
            Console.WriteLine("ENTER BRANCH DETAILS:");
            Console.WriteLine("ENTER BRANCH CODE");
            BranchCode = int.Parse(Console.ReadLine());
            Console.WriteLine("ENTER BRANCH NAME");
            BranchName = Console.ReadLine();
            Console.WriteLine("ENTER BRANCH ADDRESS");
            BranchAddress = Console.ReadLine();
        }
        public void DisplayBranchData()
        {
            Console.WriteLine("BRANCH CODE IS : " + BranchCode);
            Console.WriteLine("BRANCH NAME IS : " + BranchName);
            Console.WriteLine("BRANCH ADDRESS IS : " + BranchAddress);
        }
    }
    class Employee : Branch
    {
        int EmployeeId, EmployeeAge;
        string EmployeeName, EmployeeAddress;
        public void GetEmployeeData()
        {
            Console.WriteLine("ENTER EMPLYEE DETAILS:");
            Console.WriteLine("ENTER EMPLOYEE ID");
            EmployeeId = int.Parse(Console.ReadLine());
            Console.WriteLine("ENTER EMPLOYEE AGE");
            EmployeeAge = int.Parse(Console.ReadLine());
            Console.WriteLine("ENTER EMPLOYEE NAME");
            EmployeeName = Console.ReadLine();
            Console.WriteLine("ENTER EMPLOYEE ADDRESS");
            EmployeeAddress = Console.ReadLine();
        }
        public void DisplayEmployeeData()
        {
            Console.WriteLine("EMPLOYEE ID IS : " + EmployeeId);
            Console.WriteLine("EMPLOYEE NAME IS : " + EmployeeName);
            Console.WriteLine("EMPLOYEE ADDRESS IS : " + EmployeeAddress);
            Console.WriteLine("EMPLOYEE AGE IS : " + EmployeeAge);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Employee obj1 = new Employee();
            obj1.GetBranchData();
            obj1.GetEmployeeData();
            obj1.DisplayBranchData();
            obj1.DisplayEmployeeData();
            Console.WriteLine("Press any key to exist.");
            Console.ReadKey();
        }
    }
}

OUTPUT:

Inheritance in C#

In the above example, we made the functions GetEmployeeData() and DisplayEmployeeData() of class Branch as public because to access from outside the class i.e. from Class Employee.

And the data field BranchCode, BranchName, and BranchAddress are private by default so they are accessible within the same class only.

But if you don’t want to give accessibility of the base class members to the non-derived class (in this case class Program) and would like to give derived class (Employee) then we need to use protected to the members.

And our code would be like as…
namespace InheritanceDemo
{
    class Branch
    {
        int BranchCode;
        string BranchName, BranchAddress;
        protected void GetBranchData()
        {
            Console.WriteLine("ENTER BRANCH DETAILS:");
            Console.WriteLine("ENTER BRANCH CODE");
            BranchCode = int.Parse(Console.ReadLine());
            Console.WriteLine("ENTER BRANCH NAME");
            BranchName = Console.ReadLine();
            Console.WriteLine("ENTER BRANCH ADDRESS");
            BranchAddress = Console.ReadLine();
        }
        protected void DisplayBranchData()
        {
            Console.WriteLine("BRANCH CODE IS : " + BranchCode);
            Console.WriteLine("BRANCH NAME IS : " + BranchName);
            Console.WriteLine("BRANCH ADDRESS IS : " + BranchAddress);
        }
    }
    class Employee : Branch
    {
        int EmployeeId, EmployeeAge;
        string EmployeeName, EmployeeAddress;
        public void GetEmployeeData()
        {
            //to call the base class method use base keyword
            base.GetBranchData();
            Console.WriteLine("ENTER EMPLYEE DETAILS:");
            Console.WriteLine("ENTER EMPLOYEE ID");
            EmployeeId = int.Parse(Console.ReadLine());
            Console.WriteLine("ENTER EMPLOYEE AGE");
            EmployeeAge = int.Parse(Console.ReadLine());
            Console.WriteLine("ENTER EMPLOYEE NAME");
            EmployeeName = Console.ReadLine();
            Console.WriteLine("ENTER EMPLOYEE ADDRESS");
            EmployeeAddress = Console.ReadLine();
        }
        public void DisplayEmployeeData()
        {
            base.DisplayBranchData();
            Console.WriteLine("EMPLOYEE ID IS : " + EmployeeId);
            Console.WriteLine("EMPLOYEE NAME IS : " + EmployeeName);
            Console.WriteLine("EMPLOYEE ADDRESS IS : " + EmployeeAddress);
            Console.WriteLine("EMPLOYEE AGE IS : " + EmployeeAge);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Employee obj1 = new Employee();
            //Here we cannot access the Branch class method as they are now protected
            // obj1.GetBranchData(); //Will give Compile time error
            obj1.GetEmployeeData();
            // obj1.DisplayBranchData(); // will give compile time error
            obj1.DisplayEmployeeData();
            Console.WriteLine("Press any key to exist.");
            Console.ReadKey();
        }
    }
}

OUTPUT:

Inheritance in C#

There is no difference in the output as shown in the above image.

Note: We will specify all the common fields, properties, the method in the base class, which allows reusability. In the derived class we only have fields, properties, and methods that are specific to them.

Let’s understand this with one example.
namespace InheritanceDemo
{
    public class Employee
    {
        public string FirstName;
        public string LastName;
        public string Email;
        public void PrintEmploeeDetails()
        {
            Console.WriteLine("First Name " + FirstName + " Last Name" + LastName + " Email" + Email);
        }
    }
    public class FullTimeEmployee : Employee
    {
        public float YearlySalary;
    }
    public class PartTimeEmployee : Employee
    {
        public float HourlySalary;
    }
    public class Program
    {
        public static void Main()
        {
            FullTimeEmployee FTE = new FullTimeEmployee();
            FTE.FirstName = "Pranaya";
            FTE.LastName = "Rout";
            FTE.YearlySalary = 500000;
            FTE.Email = "abc@a.com";
            FTE.PrintEmploeeDetails();

            PartTimeEmployee PTE = new PartTimeEmployee();
            PTE.FirstName = "Mitali";
            PTE.LastName = "Rout";
            PTE.HourlySalary = 250000;
            PTE.Email = "pqr@a.com";
            PTE.PrintEmploeeDetails();

            Console.WriteLine("Press any key to existy");
            Console.ReadKey();
        }
    }
}

OUTPUT:

Inheritance in C#

How to make use of inheritance in application development?

Generally, when we develop an application we will be following a process as follows.

  1. Identify the entity that associated in the application
  2. Identify the attribute that is associated with the application.
  3. Now separate the attribute of each entity in a hierarchical order without having any duplicate.
  4. Convert those entities into classes.

Example: Suppose we are developing an application for school the attributes of the entity will be as following

Inheritance in C#

Now separate the attribute of that entity based on the hierarchy as follows.

Inheritance in C#

Now define the class representing the entity as following
namespace InheritanceDemo
{
    public class Person
    {
        int Id;
        string Name;
        string Address;
        string Phone;
    }
    public class Student : Person
    {
        string Class;
        string Fees;
        string Marks;
        string Grade;
    }
    public class Staff : Person
    {
        string Designation;
        double Salary;
    }
    public class Technical : Staff
    {
        string Qualification;
        string Subject;
    }
    public class NonTechnical : Staff
    {
        string Dname;
        string Superior;
    }
}

Please read the below MSDN article for more information regarding inheritance.

https://docs.microsoft.com/en-us/dotnet/csharp/tutorials

SUMMARY:

In this article, I try to explain Inheritance in C# step by step with some simple examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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