Inheritance in C#.Net

 

Inheritance is a relationship between minimum of two classes and one class is the parent and the second is the child. The relationship between parent and child is also called super class and subclass, where super class is synonymous with parent and subclass is synonymous with child. This parent-child relationship is called as IsArelationship.

 

When you define an inheritance relationship in C#, the child class gets all of the members defined in the parent class. When you inherit, you get all of the fields, properties, and methods defined in the parent.

 

To indicate that class Y inherits from class X, you have to write the class header as follows:

Public class B : A

 

Here we discuss inheritance in C# with simple example. Create Console Application by using Visual Studio and Add two classes Employee.cs and Manager.cs classes as shown below.

 

namespace InheritanceExp

{

    class Employee

    {

        public string GetName(int Id)

        {

            return "Employee Name";

        }

    }

}

 

namespace InheritanceExp

{

    class Manager:Employee

    {

        public string GetPermissions(int Id)

        {

            return "Manager Permissions";

        }

    }

}

 

Here Manager Class inheriting the Employee class, so Employee class is the Parent and Manager Class is the Child. You can access parent class methods by creating the object for child class in client as shown below.

 

namespace InheritanceExp

{

    class Program

    {

        static void Main(string[] args)

        {

            Manager obj = new Manager();

 

            Console.WriteLine("Emplyee Name: " + obj.GetName(100));//accessing base class method GetName()

            Console.WriteLine("Manager Permissions: " + obj.GetPermissions(100));

 

            Console.ReadLine();

        }

    }

}

 

The output displays by calling both parent class method and child class method as shown below.

 

 

                                                                                                             InheritanceExp.zip (21.73 kb)