C# is an object-oriented language that supports inheritance. It supports single class inheritance, but not multiple class inheritance.
Inheritance offers reusability. This means that the functions and variables already declared in one class can be reused in another class by making it a child of that class. This prevents the need for redundant code in the new class that is declared.
Inheritance involves the use of base and derived classes.
If both the base class and the derived class have a function of the same name, the method associated with the derived class will be executed and the inherited function will be over-ridden. For this, the derived class function must have the same name, same parameters, and same return type (or sub-type) as a method in its base class.
The following code snippet shows how inheritance works in C#:
// Inheritance in C#using System;namespace InheritanceApplication {// this is the base classpublic class Educative {// constructor of base classpublic Educative() {Console.WriteLine("Base class constructor");}// method of the base classpublic int base_adder(int x, int y) {Console.WriteLine("Using method of base class:");int sum = x + y;return sum;}}// this is the derived classpublic class Edpresso: Educative {// constructor of derived classpublic Edpresso() {Console.WriteLine("Derived class constructor");}}class Tester {static void Main(string[] args) {// creating object of base classEducative Edu = new Educative();// creating object of derived classEdpresso Edp = new Edpresso();// calling the method of super class using sub class objectint added = Edp.base_adder(2,3);Console.WriteLine("sum = {0}", added);}}}
If you look at the output of the code snippet above, you will notice the following:
Base class constructor
Base class constructor
Derived class constructor
A constructor is a class method that is accessed automatically when an instance of a class is declared. Here, we declare an instance of the base class, and “Base class constructor” is printed.
When we declare an instance of the derived class, as it is inheriting from the base class, it will first access the base class constructor, then its own constructor. This leads to the output:
Base class constructor
Derived class constructor
Free Resources