C# Inheritance

Introduction

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class to inherit properties and methods from another class. The class that inherits is called the derived class (or child class), and the class from which it inherits is called the base class (or parent class). Inheritance promotes code reusability and establishes a natural hierarchy between classes.

How Inheritance Works

  • Base Class: The class whose members are inherited.
  • Derived Class: The class that inherits members from the base class.

Syntax

public class BaseClass
{
    // Base class members
}

public class DerivedClass : BaseClass
{
    // Derived class members
}

Example

Let’s consider an example where we have a base class Animal and a derived class Dog.

using System;

namespace InheritanceExample
{
    // Base class
    public class Animal
    {
        public string Name { get; set; }

        public void Eat()
        {
            Console.WriteLine($"{Name} is eating.");
        }
    }

    // Derived class
    public class Dog : Animal
    {
        public void Bark()
        {
            Console.WriteLine($"{Name} is barking.");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Dog myDog = new Dog();
            myDog.Name = "Buddy";
            myDog.Eat(); // Inherited method from Animal class
            myDog.Bark(); // Method of Dog class
        }
    }
}

Output

Buddy is eating.
Buddy is barking.

Types of Inheritance

  1. Single Inheritance
  2. Multilevel Inheritance
  3. Hierarchical Inheritance
  4. Multiple Inheritance (via interfaces in C#)
  5. Hybrid Inheritance (combination of two or more types)

1. Single Inheritance

In single inheritance, a class inherits from only one base class.

Example

public class Vehicle
{
    public void Start()
    {
        Console.WriteLine("Vehicle started.");
    }
}

public class Car : Vehicle
{
    public void Drive()
    {
        Console.WriteLine("Car is driving.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car();
        myCar.Start(); // Inherited from Vehicle
        myCar.Drive(); // Car's own method
    }
}

Output

Vehicle started.
Car is driving.

2. Multilevel Inheritance

In multilevel inheritance, a class is derived from another derived class.

Example

public class LivingBeing
{
    public void Breathe()
    {
        Console.WriteLine("Living being is breathing.");
    }
}

public class Mammal : LivingBeing
{
    public void Walk()
    {
        Console.WriteLine("Mammal is walking.");
    }
}

public class Human : Mammal
{
    public void Speak()
    {
        Console.WriteLine("Human is speaking.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Human person = new Human();
        person.Breathe(); // Inherited from LivingBeing
        person.Walk(); // Inherited from Mammal
        person.Speak(); // Human's own method
    }
}

Output

Living being is breathing.
Mammal is walking.
Human is speaking.

3. Hierarchical Inheritance

In hierarchical inheritance, multiple classes inherit from a single base class.

Example

public class Shape
{
    public void Draw()
    {
        Console.WriteLine("Drawing shape.");
    }
}

public class Circle : Shape
{
    public void DrawCircle()
    {
        Console.WriteLine("Drawing circle.");
    }
}

public class Rectangle : Shape
{
    public void DrawRectangle()
    {
        Console.WriteLine("Drawing rectangle.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Circle circle = new Circle();
        circle.Draw(); // Inherited from Shape
        circle.DrawCircle(); // Circle's own method

        Rectangle rectangle = new Rectangle();
        rectangle.Draw(); // Inherited from Shape
        rectangle.DrawRectangle(); // Rectangle's own method
    }
}

Output

Drawing shape.
Drawing circle.
Drawing shape.
Drawing rectangle.

4. Multiple Inheritance (via Interfaces)

C# does not support multiple inheritance directly but allows it through interfaces.

Example

public interface IPrintable
{
    void Print();
}

public interface IScannable
{
    void Scan();
}

public class MultiFunctionPrinter : IPrintable, IScannable
{
    public void Print()
    {
        Console.WriteLine("Printing document.");
    }

    public void Scan()
    {
        Console.WriteLine("Scanning document.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        MultiFunctionPrinter mfp = new MultiFunctionPrinter();
        mfp.Print(); // Implemented from IPrintable
        mfp.Scan(); // Implemented from IScannable
    }
}

Output

Printing document.
Scanning document.

Method Overriding

Method overriding allows a derived class to provide a specific implementation of a method that is already defined in its base class. It is achieved using the virtual keyword in the base class and the override keyword in the derived class.

Example

public class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("Animal makes a sound.");
    }
}

public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Dog barks.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Animal myAnimal = new Animal();
        myAnimal.MakeSound(); // Outputs: Animal makes a sound.

        Dog myDog = new Dog();
        myDog.MakeSound(); // Outputs: Dog barks.

        Animal myPet = new Dog();
        myPet.MakeSound(); // Outputs: Dog barks.
    }
}

Output

Animal makes a sound.
Dog barks.
Dog barks.

Base Keyword

The base keyword is used to access members of the base class from within a derived class. It is useful for calling base class constructors and methods.

Example

public class Person
{
    public string Name { get; set; }

    public Person(string name)
    {
        Name = name;
    }

    public virtual void Display()
    {
        Console.WriteLine($"Person Name: {Name}");
    }
}

public class Employee : Person
{
    public int EmployeeID { get; set; }

    public Employee(string name, int employeeID) : base(name)
    {
        EmployeeID = employeeID;
    }

    public override void Display()
    {
        base.Display();
        Console.WriteLine($"Employee ID: {EmployeeID}");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Employee emp = new Employee("John Doe", 12345);
        emp.Display();
    }
}

Output

Person Name: John Doe
Employee ID: 12345

Conclusion

Inheritance in C# is a powerful feature that promotes code reusability and establishes a hierarchical relationship between classes. By understanding the different types of inheritance and how to use method overriding and the base keyword, you can create more organized and maintainable code. Inheritance is a cornerstone of object-oriented programming, and mastering it is essential for building robust applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top