Inheritance in C#

The process of creating one class from another class is called as inheritance.

Inheritance is one of the fundamental principles of object-oriented programming. It enables you to create new class from existing class. Reusability is the main advantage of inheritance.

C# does not support multiple inheritance.

The class that is inherited is called as base class and the class that does the inheritance is called as derived class. Derived class inherits all data member and member function defined by the base class and adds its own unique members. Constructor and destructor do not inherited.

Syntax

[Access Modifier] class DerivedClassName : BaseClassName  
{
  // Your code goes here.
}


Example

using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
    public class Employee
    {
        public Employee()
        {  
            this.ID = 0;
            this.Name = "N/A";           
        }
        public Employee(int id, string name)
        {
            this.ID = id;
            this.Name = name;
        }
        public int ID { get;set; }
        public string Name { get;set; }
        public void getData()
        {
            Console.WriteLine("Enter the Employee ID");
            ID = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter the Employee Name");
            Name =Console.ReadLine();
        }

        public void showData()
        {
            Console.WriteLine("\n Employee ID = "+ ID);
            Console.WriteLine(" Employee Name = " + Name);
        }       
    }
    class Manager : Employee
    {
        public Manager()
        {
            Role="N/A";
        }
        public string Role { get; set; }
        public void getRole()
        {
            Console.WriteLine("Enter the Employee Role");
            Role = Console.ReadLine();
        }
        public void showRole()
        {
            Console.WriteLine(" Employee Role is " +Role);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Manager obj = new Manager();
            obj.getData();
            obj.getRole();
            obj.showData();
            obj.showRole();       
     
            Console.ReadLine();
        }
    }
}


In the above code Employee is the base class and Manager is the derived class. In employee class, two public auto implemented property (ID and Name) and two public methods getData() and showData() are available.

In Manager class one property name as Role and two method getRole() and showRole() is available. Because manager class is inherited from employee class, therefore employee object now have three property and four methods. Object of manager class can directly refer the data member and member function of employee class.

inheritance-output

A derived class cannot access private member of base class. By default data member and member function of class are private.

Using Protected Access

A protected member performs as public within a class hierarchy, but private outside that hierarchy. If you declare a member as protected then, protected status will continue with that member in all layers of inheritance.

class BaseClase
{
        protected int  intVar;
        …….
        …….
}
Class DerivedClass : BaseClase
{
        // intVar is protected here.
        …….
        …….

}
Class MostDerivedClass : DerivedClass
{
       // intVar is protected here.
       …….
       …….

}


Constructors and Inheritance

Constructor and destructor are not inherited. The base class constructor constructs the base class portion of the object, and the constructor for the derived class constructs the object of derived class.

A derived class constructor always call base class constructor.

Syntax


derivedClass-constructor (parameter-list) : base(arg-list)
{
     // body of constructor
}


Example

using System;
namespace ConsoleApplication1
{
    class BaseClase
    {
        public BaseClase()
        {
            Console.WriteLine("Base Class constructor is called");
        }
    }
    class DerivedClass : BaseClase
    {
        public DerivedClass()
        {
            Console.WriteLine("Derived Class constructor is called");
        }
    }
    class MostDerivedClass : DerivedClass
    {
        public MostDerivedClass()
        {
            Console.WriteLine("MostDerived Class  constructor is called");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            MostDerivedClass obj = new MostDerivedClass();
            Console.ReadLine();
        }
    }
}


Output:
Base Class constructor is called
Derived Class constructor is called
MostDerived Class constructor is called

In multilevel inheritance, constructor is always executed from base class to derived class. Most derived class constructor calls the next upper class constructor and so on.

If you want to pass some parameter from derived class constructor to base class constructor, then use base keyword.

class MostDerivedClass : DerivedClass
    {
        public MostDerivedClass():base(int a)
        {
            // Constructor code
        }
    }


Name Hiding in Inheritance

Sometimes you declare the same name member in base and derived class. It is not an error in C# but visual studio gives warning that “use the new keyword if hiding was intended”.

In this situation, the member in the base class is hidden within the derived class. You can avoid this warning by using new keyword with the same name derived class member.

Here, use of new keyword is entirely different while creating an object instance.
Still if you need base class member, then you can use base keyword.

Example

using System;
namespace ConsoleApplication1
{
    class BaseClase
    {
        public int intVar=100;       
    }
    class DerivedClass : BaseClase
    {
        new int intVar;         //this intVar hides the intVar in BaseClass
        public DerivedClass(int a)
        {
            intVar = a;
        }
        public void show()
        {
            Console.WriteLine("intVar from derived class and value =" + intVar);
            // base.intVar will access the value of base class variable
            Console.WriteLine("intVar from base class and value =" + base.intVar);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            DerivedClass obj = new DerivedClass(10);
            obj.show();
            Console.ReadLine();
        }
    }
}


Sealed class

Sometimes you want that users of your class should not able to inherit your class, in that case you can append sealed keyword with class. Sealed keyword provides the functionality that no one can inherit your class.

You cannot use sealed and abstract keyword simultaneously. Abstract class always works as base class. It is incomplete class and depends upon its derived classes to provide complete implementations.

Here is an example of a sealed class:

Example

sealed class BaseClase
    {
       // ………
    }
      //ERROR! Can't derive from class BaseClase.
     // BaseClass is sealed class
    class DerivedClass : BaseClase  
    {
      // ………..
    }


You can also use sealed keyword with method and properties but it should be declare with override. The sealed modifier must always be used with override.

Example

using System;

namespace ConsoleApplication1
{
     class BaseClase
    {       
        public virtual void show()
        {
            // Your implementation.
           //  ……….
        }
    }
    class DerivedClass : BaseClase
    {
        sealed public override void show()
        {
              // Your implementation.
              //  ……….

        }
    }
    class MostDerivedClass : DerivedClass
    {
        //Attempting to override show causes compiler error
        sealed public override void show()
        {
              // Your implementation.
              //  ……….
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            MostDerivedClass obj = new MostDerivedClass();            
            Console.ReadLine();
        }
    }
}


In the above example, show() method is declared as virtual in BaseClass and override in DerivedClass. In DerivedClass it is decorated with sealed, therefore you cannot use show() method in  MostDerivedClass class. It will give comile time error.

Error: You cannot override inherited member because it is sealed.

Note: sealed can be used on virtual methods and virtual properties to prevent further overrides.