;

C# Inheritance


Inheritance is one of the core concepts of Object-Oriented Programming (OOP). In C#, inheritance allows a class to inherit properties, methods, and behavior from another class. This reduces redundancy, promotes code reusability, and allows for the creation of a clear hierarchical structure.

In this detailed tutorial, we will explore the concept of inheritance in C#, discuss the different types of inheritance, walk through examples with use cases and provide a real-world example.

What is Inheritance in C#?

Inheritance is a mechanism by which one class (called the derived class or child class) can acquire the properties and behaviors (methods) of another class (called the base class or parent class). This allows the derived class to reuse code from the base class, extend or modify functionality, and create a class hierarchy.

Key Points:

  • The base class contains common functionality, while derived classes extend or override this functionality.
  • Inheritance promotes code reuse, reduces redundancy, and maintains a clear structure.
  • C# supports single inheritance (a class can inherit from only one base class) but not multiple inheritance (a class cannot inherit from more than one base class directly).

Types of Inheritance

Single Inheritance

In single inheritance, a class inherits from only one base class. This is the most common form of inheritance.

Example:

class Animal
{
    public void Eat()
    {
        Console.WriteLine("Eating...");
    }
}

class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("Barking...");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Dog dog = new Dog();
        dog.Eat();  // Inherited from Animal
        dog.Bark(); // Defined in Dog
    }
}

Multilevel Inheritance

In multilevel inheritance, a class can inherit from a class that has already inherited from another class. This creates a chain of inheritance.

Example:

class LivingBeing
{
    public void Breathe()
    {
        Console.WriteLine("Breathing...");
    }
}

class Animal : LivingBeing
{
    public void Eat()
    {
        Console.WriteLine("Eating...");
    }
}

class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("Barking...");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Dog dog = new Dog();
        dog.Breathe(); // Inherited from LivingBeing
        dog.Eat();     // Inherited from Animal
        dog.Bark();    // Defined in Dog
    }
}

Hierarchical Inheritance

In hierarchical inheritance, multiple classes inherit from the same base class.

Example:

class Animal
{
    public void Eat()
    {
        Console.WriteLine("Eating...");
    }
}

class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("Barking...");
    }
}

class Cat : Animal
{
    public void Meow()
    {
        Console.WriteLine("Meowing...");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Dog dog = new Dog();
        Cat cat = new Cat();

        dog.Eat();  // Inherited from Animal
        dog.Bark(); // Defined in Dog

        cat.Eat();  // Inherited from Animal
        cat.Meow(); // Defined in Cat
    }
}

Multiple Inheritance (Not Supported Directly)

C# does not support multiple inheritance directly (i.e., a class cannot inherit from more than one class). However, this can be achieved using interfaces.

Examples of Inheritance in C#

Example 1: Single Inheritance

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

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

class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car();
        myCar.Drive(); // Output: Vehicle is driving...
        myCar.Honk();  // Output: Car is honking...
    }
}

Example 2: Multilevel Inheritance

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

class Mammal : LivingBeing
{
    public void NurseYoung()
    {
        Console.WriteLine("Mammal is nursing its young...");
    }
}

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

class Program
{
    static void Main(string[] args)
    {
        Human person = new Human();
        person.Grow();      // Inherited from LivingBeing
        person.NurseYoung(); // Inherited from Mammal
        person.Speak();      // Defined in Human
    }
}

Example 3: Hierarchical Inheritance

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

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

class Bike : Vehicle
{
    public void KickStart()
    {
        Console.WriteLine("Bike is being kick-started...");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Car car = new Car();
        Bike bike = new Bike();

        car.Drive();     // Inherited from Vehicle
        car.Fuel();      // Defined in Car

        bike.Drive();    // Inherited from Vehicle
        bike.KickStart(); // Defined in Bike
    }
}

Real-World Example: E-commerce Application

Let’s imagine an e-commerce system where we have different types of users, such as Admin, Customer, and Guest, all inheriting from a base class User.

class User
{
    public string Username { get; set; }

    public void Login()
    {
        Console.WriteLine($"{Username} logged in.");
    }
}

class Admin : User
{
    public void AccessAdminPanel()
    {
        Console.WriteLine("Admin has access to admin panel.");
    }
}

class Customer : User
{
    public void PlaceOrder()
    {
        Console.WriteLine("Customer placed an order.");
    }
}

class Guest : User
{
    public void BrowseProducts()
    {
        Console.WriteLine("Guest is browsing products.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Admin admin = new Admin { Username = "AdminUser" };
        Customer customer = new Customer { Username = "CustomerUser" };
        Guest guest = new Guest { Username = "GuestUser" };

        admin.Login();          // Output: AdminUser logged in.
        admin.AccessAdminPanel(); // Output: Admin has access to admin panel.

        customer.Login();       // Output: CustomerUser logged in.
        customer.PlaceOrder();  // Output: Customer placed an order.

        guest.Login();          // Output: GuestUser logged in.
        guest.BrowseProducts(); // Output: Guest is browsing products.
    }
}

Explanation:

  • We have a base class User with common functionality, such as Login.
  • Derived classes Admin, Customer, and Guest each inherit from User and provide their own specific behaviors.
  • This approach reduces code duplication and ensures that common functionality like Login is consistent across all user types.

Key Takeaways

  1. Inheritance allows one class to reuse the properties and methods of another class, promoting code reuse and reducing redundancy.
  2. Single Inheritance involves a class inheriting from a single base class.
  3. Multilevel Inheritance creates a chain of inheritance where a class inherits from a derived class.
  4. Hierarchical Inheritance involves multiple classes inheriting from the same base class.
  5. C# does not support multiple inheritance directly, but it can be implemented using interfaces.
  6. Inheritance establishes a clear relationship between classes and helps maintain consistency across the system.
  7. Overriding base class methods using virtual and override allows derived classes to customize inherited behavior.

Summary

In C#, inheritance is a fundamental OOP principle that allows for reusing code and extending functionality. By inheriting from a base class, derived classes gain access to its methods and properties, reducing code duplication and enhancing maintainability. We explored several types of inheritance, including single, multilevel, and hierarchical inheritance, and discussed how C# does not support multiple inheritance directly. Through examples and real-world use cases, we’ve demonstrated how inheritance can simplify complex systems by promoting reusability and extensibility.

Understanding and leveraging inheritance allows developers to create more structured, maintainable, and scalable applications in C#.