C# Inheritance

Updated on     Kisan Patel

The most important reason to use Object Oriented Programmng is to promote reusability of code and eliminate the redundant code. To reduce redundancy, the OOP support inheritance.

Inheritance is the property through which a class derives properties from another class. So, The process of sub-classing a class to extend its functionality is called Inheritance.

The original class is called the base, parent or super class. The class that inherits the functionality of the class and extends it in its own way is called the sub, child, derived or inherited class.

Inheritance

If a class B (sub-class) inherits a class A (base-class), then B would have a copy of all the instance members(fields, methods, properties) of class A and B can access all the members (except for the private members) of class A.

C# does not support multiple inheritance. To implement multiple inheritance, you need to use interfaces.

Note : An interface is a collection of data members and member functions, but it only contains the declaration of data members and member functions.

C# uses the colon ‘:’ operator to indicate inheritance.

For example, the Animal class can be a base class for a number of derived classes such as Dog and Tiger.

public class Animal
{
    public void Greet()
    {
        Console.WriteLine("Hello, This is Base class!");
    }
}

public class Dog : Animal
{
    ....
}
public class Tiger : Animal
{
    ....
}

Let’s take one example to understand inheritance in C#.

using System;

namespace ConsoleApp
{
    public class Student
    {
        public int rollNumber;
        public string name;
        public DateTime dateOfBirth;
        public void GetStudentName()
        {
            Console.WriteLine("Name of Student : " + name);
        }
    }

    public class StudentDetails : Student
    {
        public void GetStudentDetails()
        {
            Console.WriteLine("Student Roll No : " + rollNumber);
            Console.WriteLine("Student Date of Birth : " + dateOfBirth);
        }
    }

    public class Tester
    {
        public static void Main(string[] args)
        {
            Student s = new Student();
            StudentDetails std = new StudentDetails();
            std.rollNumber = 15;
            s.name = "Kisan Patel";
            std.dateOfBirth = new DateTime(1990, 5, 26);
            s.GetStudentName();
            std.GetStudentDetails();
        }
    }
}

Suppose we have a class Student with rollNumber, name and dateofBirth fields. The class also has method GetStudentName() which display student name.

We have also StudentDetails class which inherited from the Student class. So StudentDetails class are able to access the properties and methods defined in Student class.

When we execute the above C# program, we get the following output.

c-sharp-interface-example


C#

Leave a Reply