Inheritance in C#

Spread the love

Inheritance is the most crucial concept When diving into object-oriented programming (OOP) in C#.   It is a very powerful tool that allows you to reusability of code, easy to maintain and efficient code.  In this blog, you will understand what inheritance is, why it’s essential, and the different types of inheritance in C#. We will also see the practical example of each inheritance.

What is Inheritance in C#?

Inheritance is a feature of OOP that allows a class to inherit properties and methods from another class. This creates a relationship between classes, where one class (known as the base class or parent) shares its functionality with another class (known as the derived class or child). The derived class can then use, extend, or modify this inherited functionality to suit its needs.

Let’s understand with a small example. You have a blueprint of the car with wheels, an engine, and seats. Now, you want to build different types of cars like sports cars or trucks. Instead of redesigning everything from scratch, you start with the basic car design and add features specific to the sports car or truck.

Benefits of Inheritance

1) Reuse code efficiently

2) It reduces code redundancy

3) Reduces source code size and improves code readability.

4) Easy to maintain code as changes made in the parent class are automatically reflected in the child class. 

5) It also allows for extensibility. You can add new classes and features without rewriting everything.

Types of Inheritance in C#

1) Single Inheritance

2) Multilevel Inheritance

3) Hierarchical Inheritance

4) Multiple Inheritance (not directly supported, but achievable through interfaces)

5) Hybrid Inheritance

1. Single Inheritance

Single inheritance refers to a class that inherits from one base class. It’s the most straightforward type of inheritance, where a derived class extends a single-parent class.

// Base class (parent)
public class Animal
{
    public void Eat()
    {
        Console.WriteLine("This animal is eating.");
    }
}

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

public class SingleInheritanceDemo
{
    public static void Main(string[] args)
    {
        // Single inheritance
        Dog dog = new Dog();
        dog.Eat();  // Inherited from Animal
        dog.Bark(); // Specific to Dog
    }
}

Output:

This animal is eating. 

The dog is barking.

In the above example

  • The Animal class is the base class with the method Eat().
  • The Dog class inherits from the Animal class and gets the Eat() method. Additionally, it has its own method Bark().

2. Multilevel Inheritance

Multilevel inheritance occurs when a class is derived from a class that is already derived from another class. This creates a chain of inheritance, where each class can build on the functionality of its parent and grandparent classes.

// Base class
public class Animal
{
    public void Eat()
    {
        Console.WriteLine("This animal is eating.");
    }
}

// Derived class
public class Mammal : Animal
{
    public void Walk()
    {
        Console.WriteLine("This mammal is walking.");
    }
}

// Further derived class
public class Dog : Mammal
{
    public void Bark()
    {
        Console.WriteLine("The dog is barking.");
    }
}

public class MultilevelInheritanceDemo
{
    public static void Main(string[] args)
    {
        // Multilevel inheritance
        Dog dog = new Dog();
        dog.Eat();   // Inherited from Animal
        dog.Walk();  // Inherited from Mammal
        dog.Bark();  // Specific to Dog
    }
}

Output:

This animal is eating.

This mammal is walking.

The dog is barking.

In the above example

  • The Animal class is the base class.
  • The Mammal class inherits from Animal and adds the Walk() method.
  • The Dog class inherits from Mammal and adds the Bark() method, but can still access the Walk() and Eat() methods.

3. Hierarchical Inheritance

In hierarchical inheritance, multiple derived classes inherit from the same base class. This structure is useful when you define a set of shared behaviours in the base class that various derived classes can inherit.

// Base class
public class Animal
{
    public void Eat()
    {
        Console.WriteLine("This animal is eating.");
    }
}

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

// Derived class 2
public class Cat : Animal
{
    public void Meow()
    {
        Console.WriteLine("The cat is meowing.");
    }
}

public class HierarchicalInheritanceDemo
{
    public static void Main(string[] args)
    {
        // Hierarchical inheritance
        Dog dog = new Dog();
        dog.Eat();   // Inherited from Animal
        dog.Bark();  // Specific to Dog

        Cat cat = new Cat();
        cat.Eat();   // Inherited from Animal
        cat.Meow();  // Specific to Cat
    }
}

Output:

This animal is eating.

The dog is barking.

This animal is eating.

The cat is meowing.

In the above example

  • Both Dog and Cat inherit from the Animal class. They can both use the Eat() method but also have their own specific methods (Bark() and Meow()).

4. Multiple Inheritance (via Interfaces)

While C# doesn’t support multiple inheritance directly (where a class inherits from more than one base class), you can achieve a similar effect using interfaces. Interfaces allow a class to implement multiple sets of behaviour, giving you the flexibility of multiple inheritances without the complexity.

// Interface 1
public interface ICanBark
{
    void Bark();
}

// Interface 2
public interface ICanRun
{
    void Run();
}

// Class implementing multiple interfaces
public class Dog : ICanBark, ICanRun
{
    public void Bark()
    {
        Console.WriteLine("The dog is barking.");
    }

    public void Run()
    {
        Console.WriteLine("The dog is running.");
    }
}
public class MultipleInheritanceDemo
{
    public static void Main(string[] args)
    {
        // Multiple inheritance via interfaces
        Dog dog = new Dog();
        dog.Bark(); // From ICanBark
        dog.Run();  // From ICanRun
    }
}

Output:

The dog is barking.

The dog is running.

In the above example

  • The Dog class implements two interfaces, ICanBark and ICanRun, meaning it must define the Bark() and Run() methods.
  • This allows Dog to “inherit” behaviours from multiple sources (interfaces).

5. Hybrid Inheritance

Hybrid inheritance is a combination of two or more types of inheritance. It may involve hierarchical, multilevel, or even interface-based inheritance. While C# does not directly support multiple inheritance through classes, hybrid inheritance can be achieved through a mix of classes and interfaces.

// Base class
public class Animal
{
    public void Eat()
    {
        Console.WriteLine("This animal is eating.");
    }
}

// Derived class
public class Mammal : Animal
{
    public void Walk()
    {
        Console.WriteLine("This mammal is walking.");
    }
}

// Interface
public interface ICanSwim
{
    void Swim();
}

// Derived class from Mammal and implementing an interface
public class Dolphin : Mammal, ICanSwim
{
    public void Swim()
    {
        Console.WriteLine("The dolphin is swimming.");
    }
}

public class HybridInheritanceDemo
{
    public static void Main(string[] args)
    {
        // Hybrid inheritance
        Dolphin dolphin = new Dolphin();
        dolphin.Eat();   // Inherited from Animal (via Mammal)
        dolphin.Walk();  // Inherited from Mammal
        dolphin.Swim();  // From ICanSwim
    }
}

Output:

This animal is eating.

This mammal is walking.

The dolphin is swimming.

In the above example

The Dolphin class inherits from Mammal (multilevel inheritance) and implements the ICanSwim interface, combining both class inheritance and interface-based inheritance.

Conclusion

Above blog, you can easily understand the concept of inheritance. Inheritance is a core concept of object-oriented programming and it is frequently used in applications. By using different types of inheritance, you can efficiently manage and extend the functionality of your applications. Inheritance not only simplifies your code but also makes it easier to maintain and extend over time.

To summarize the key takeaways:

  • Single inheritance allows a class to inherit from one base class.
  • Multilevel inheritance forms a chain of inheritance where each class builds on the previous one.
  • Hierarchical inheritance lets multiple classes inherit from the same base class.
  • Multiple inheritance can be achieved using interfaces in C#.
  • Hybrid inheritance combines different inheritance types for more flexible code structures.


Spread the love