What is Inheritance in C#?

What is Inheritance in C#?
Rating: 5 - 1 Votes

What is Inheritance in C#?

What is Inheritance in C#?

What is Inheritance in C#?

Before we start digging into the inheritance topic, you must need to know there are 4 pillars to object oriented programming.

  1. Inheritance
  2. Encapsulation
  3. Abstraction
  4. Polymorphism

However, in this session, we will discuss only inheritance.  Lets take a very small example to start this concept.  Suppose you have to create a report about 10 students.  Every student has a first name and last name.  Now, in this case you will end up with creating 10 classes, which contains 2 common fields for first name and last name.  Now, if we encounter any error related to first name and last name, then we have to fix it in all the 10 classes.  But in C# with the help of inheritance, we can create a single class which contains most of the common code like first name and last name fields, known as base class or parent class.  All the other classes can inherit that code from the base or parent class.  The classes which inherit the code known as derived class or child class.  In C#, inheritance helps in code reusability and the probability of number of errors while coding will be less.

To make use of inheritance, you have to use colon (:) after the name of derived class following base class name.  C# only supports single class inheritance or multilevel class inheritance, multiple class inheritance is not allowed.  In multilevel inheritance, a derived class behaves like a parent class for another class, which further inherits from it.  C# does support multiple interface inheritance.

Whenever you create an object of a derived class, the base class constructor will be called first, then derived class constructor.  In such a case where base class has 2 constructors, one with parameters and other without parameters, then by default, the constructor without parameters will be called.  If you want to call any other constructor in the base class, then you have to use base keyword in front of derived class constructor and pass the parameters depending upon your base class constructor.