Skip to main content
Published on

More About Inheritance in C#

Share:

Introduction

Inheritance is a fundamental pillar of object-oriented programming (OOP), allowing developers to build hierarchical relationships between classes, promoting code reuse and reducing redundancy. This article dives deeper into the concept of inheritance in C#.

Exploring Inheritance in C#

Definition and Utility

  • Inheritance is a principle by which a class (subclass or derived) extends another class (superclass or base), inheriting its properties and methods.

Benefits of Inheritance

  • Code Reuse: Inheritance allows reusing existing code, reducing duplication.
  • Code Organisation: It establishes a natural hierarchy, making the code more intuitive and manageable.

Limitations and Challenges

  • Single Inheritance: In C#, a class cannot inherit from more than one superclass. This avoids the complexity of multiple inheritance, but also limits certain design possibilities.

Keywords and Concepts

  • new: Creates instances of objects and other structures.
  • virtual: Used to define methods or properties that can be overridden in subclasses.
  • override: Allows the modification of methods or properties defined as virtual in the superclass.

Practical Example of Inheritance

Let's analyse an example where Child inherits from Parent and overrides one of its methods:

using System;

namespace Base {
  class MoreAboutInheritance {
    public void Run() {
      var person = new Child();
      person.Information();
      person.FavoriteFood();

      /*
        Name: Nelson Silva
        Age: 28
        My favorite food is lasagna.
      */
    }
  }

  class Parent {
    protected string lastName = "Silva";

    public virtual void FavoriteFood() {
      Console.WriteLine("My favorite food is seafood rice.");
    }
  }

  class Child : Parent {
    private string firstName = "Nelson";
    private int age = 28;

    public void Information() {
      Console.WriteLine($"Name: {firstName} {lastName}");
      Console.WriteLine($"Age: {age}");
    }

    public override void FavoriteFood() {
      Console.WriteLine("My favorite food is lasagna.");
    }
  }
}

Understanding the Example

  • The Child class inherits lastName from Parent, showing how attributes are passed down to the subclass.
  • The FavoriteFood method is overridden, exemplifying the customisation of inherited behaviours.

Implications of Inheritance

Inheritance, when misused, can lead to design problems such as excessive coupling between classes. It is important to apply design principles, such as SOLID, to create a robust and flexible architecture.

Conclusion

Inheritance in C# offers a powerful way to organise and reuse code, but requires understanding and care to be used efficiently. With this knowledge, you will be better prepared to create complex and maintainable systems.

Happy coding!