4 Powerful Concepts to Master Inheritance in C# Programming

Why Inheritance? 🤔

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows one class to inherit the properties and behavior of another class. This promotes code reuse, reducing the amount of code that needs to be written and tested.

Inheritance

“It is a mechanism of creating a new class from an existing class. The new class is called the derived class or subclass, and the existing class is called the base class or superclass.”

“The child class inherits all the fields, properties, and methods of the parent class and can also add new fields, properties, and methods or override the ones inherited from the parent class.”

Advantages of Inheritance

  • Code Reuse: It allows for code reuse, reducing the amount of code that needs to be written and tested.
  • Reduced Errors: With less code to write, there is less chance of errors.
  • Savings of Time: It saves time by reducing the amount of code that needs to be written and tested.

Inheritance Syntax

The syntax in C# is as follows:

public class DerivedClass : BaseClass

Example of Inheritance

ClassPropertiesMethods
EmployeeFirstName, LastName, EmailPrintFullName()
FullTimeEmployeeYearlySalary
PartTimeEmployeeHourlyRate

In this example, the FullTimeEmployee and PartTimeEmployee classes inherit the properties and methods of the Employee class.

Creating a Derived Class

public class FullTimeEmployee : Employee
{
    public float YearlySalary;
}

Accessing Base Class Members

A derived class can access the members of its base class using the dot notation.

FullTimeEmployee fte = new FullTimeEmployee();
fte.FirstName = "John";
fte.LastName = "Doe";
fte.PrintFullName();

Specialization

A derived class is a specialization of its base class, meaning it has all the capabilities of the base class plus additional capabilities specific to the derived class.

“A derived class is a specialization of its base class, just like a gynecologist is a specialization of a general surgeon.”

Implementation

To implement this, you can create a base class with common properties and methods, and then create derived classes that inherit from the base class and add their own specific properties and methods.

1. Single Class Inheritance

C# supports single class inheritance, which means a class can have only one base class at a given time.


| | Single Class Inheritance | Multiple Class Inheritance |
| —————– | —————————————- | ——————————————- |
| **Definition** | A class can have only one base class. | A class can have multiple base classes. |
| **C# Support** | Supported | Not Supported |

Example 1

public class Employee
{
    public string FirstName;
    public string LastName;
    public string Email;

    public void PrintFullName()
    {
        Console.WriteLine(FirstName + " " + LastName);
    }
}

public class FullTimeEmployee : Employee
{
    public float YearlySalary;
}

public class PartTimeEmployee : Employee
{
    public float HourlyRate;
}

2. Multilevel Class Inheritance

C# supports multilevel class inheritance, where a class can inherit from a class that itself inherits from another class.

Example 1

public class Employee
{
    // properties and methods
}

public class PartTimeEmployee : Employee
{
    // properties and methods
}

public class ClassA : PartTimeEmployee
{
    // properties and methods
}

In this example, ClassA inherits from PartTimeEmployee, which itself inherits from Employee.

Example 2

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

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

// Another derived class inheriting from Mammal (Multilevel Inheritance)
class Dog : Mammal
{
    public void Bark()
    {
        Console.WriteLine("The dog barks.");
    }
}

class Program
{
    static void Main()
    {
        Dog dog = new Dog();
        
        dog.Eat();  // Inherited from Animal
        dog.Walk(); // Inherited from Mammal
        dog.Bark(); // Specific to Dog
    }
}

Explanation:

  • The Dog class inherits from Mammal, which in turn inherits from Animal.
  • The Dog class can use methods from both the Animal and Mammal classes.

3. Hierarchical Inheritance in C#

Hierarchical inheritance in C# occurs when multiple derived classes inherit from a single base class. This type of inheritance allows shared properties and methods to be reused by multiple subclasses, avoiding code duplication.

Example 1

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

// Derived classes inheriting from Animal (Hierarchical Inheritance)
class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("The dog barks.");
    }
}

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

class Program
{
    static void Main()
    {
        Dog dog = new Dog();
        Cat cat = new Cat();
        
        dog.Eat(); // Shared method from Animal
        dog.Bark(); // Specific to Dog

        cat.Eat(); // Shared method from Animal
        cat.Meow(); // Specific to Cat
    }
}

Explanation:

  • The Dog and Cat classes both inherit from the Animal class.
  • They both have access to the Eat() method but also possess their specific methods (Bark() for Dog and Meow() for Cat).

4. Multiple Inheritance Using Interfaces in C#

In C#, a class cannot directly inherit from more than one base class.

Example 1

// Define the first interface
interface IAnimal
{
    void Eat();
}

// Define the second interface
interface IMammal
{
    void Walk();
}

// Implementing both interfaces in a single class (Multiple Inheritance)
class Dog : IAnimal, IMammal
{
    public void Eat()
    {
        Console.WriteLine("The dog is eating.");
    }

    public void Walk()
    {
        Console.WriteLine("The dog is walking.");
    }

    public void Bark()
    {
        Console.WriteLine("The dog is barking.");
    }
}

class Program
{
    static void Main()
    {
        Dog dog = new Dog();
        
        dog.Eat();  // Implemented from IAnimal
        dog.Walk(); // Implemented from IMammal
        dog.Bark(); // Class-specific method
    }
}

Explanation:

  • The IAnimal and IMammal interfaces define two different behaviors (Eat() and Walk() respectively).
  • The Dog class implements both IAnimal and IMammal, thereby providing implementations for Eat() and Walk().
  • The Dog class can also define its own behavior (Bark()).

Note: Here, you can checkout our post on 8 Types of LINQ Query in C#: Unique Capabilities and Advantages

Key Advantages of Using Interfaces for Multiple Inheritance:

  1. Separation of Concerns: Interfaces allow you to break down behaviors into smaller, reusable units.
  2. Flexibility: You can implement multiple interfaces and define your own additional functionality within the class.
  3. No Diamond Problem: Since interfaces only define contracts (without actual implementation), there’s no ambiguity when multiple interfaces define the same method signatures.

Child Class is a Specialization of Base Class

A child class is a specialization of a base class, meaning it can do everything the base class can do, plus whatever is specific to the child class.

Base Classes are Automatically Instantiated Before Derived Classes

When an instance of a child class is created, the base class is automatically instantiated before the child class.

public class ParentClass
{
    public ParentClass()
    {
        Console.WriteLine("Parent class constructor called");
    }
}

public class ChildClass : ParentClass
{
    public ChildClass()
    {
        Console.WriteLine("Child class constructor called");
    }
}

public class Program
{
    public static void Main()
    {
        ChildClass child = new ChildClass();
    }
}

Output:

Parent class constructor called
Child class constructor called

Controlling Parent Class Constructor Calls

The base keyword can be used to control which constructor is called in the parent class when an instance of the child class is created.

public class ParentClass
{
    public ParentClass()
    {
        Console.WriteLine("Parent class constructor called");
    }

    public ParentClass(string message)
    {
        Console.WriteLine(message);
    }
}

public class ChildClass : ParentClass
{
    public ChildClass() : base("Message from derived class")
    {
        Console.WriteLine("Child class constructor called");
    }
}

public class Program
{
    public static void Main()
    {
        ChildClass child = new ChildClass();
    }
}

Output:

Message from derived class
Child class constructor called

Conclusion

Summarising it all, inheritance is one of the main pillars on which object-oriented programming stands. Its aim is to make the code reusable and organized.

References

For more information and detailed references on the topics discussed in this article, please refer to the following link:

Leave a Comment

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

Scroll to Top