Start Coding

Topics

C# Inheritance

Inheritance is a crucial concept in object-oriented programming (OOP) that allows a class to inherit properties and methods from another class. In C#, it promotes code reuse and establishes a hierarchical relationship between classes.

Basic Syntax

To create a derived class in C#, use the following syntax:


class DerivedClass : BaseClass
{
    // Derived class members
}
    

The colon (:) indicates that the derived class inherits from the base class.

Types of Inheritance

  • Single Inheritance: A class inherits from one base class.
  • Multilevel Inheritance: A class inherits from a derived class.
  • Hierarchical Inheritance: Multiple classes inherit from a single base class.

C# does not support multiple inheritance for classes, but it can be achieved using interfaces.

The 'base' Keyword

Use the 'base' keyword to access members of the base class from within the derived class:


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

class Dog : Animal
{
    public override void MakeSound()
    {
        base.MakeSound(); // Call the base class method
        Console.WriteLine("The dog barks");
    }
}
    

Constructors in Inheritance

When a derived class is instantiated, the base class constructor is called first. You can explicitly call a base class constructor using the 'base' keyword:


class Animal
{
    public Animal(string name)
    {
        Console.WriteLine($"Animal constructor: {name}");
    }
}

class Dog : Animal
{
    public Dog(string name) : base(name)
    {
        Console.WriteLine($"Dog constructor: {name}");
    }
}
    

Access Modifiers and Inheritance

Inheritance respects access modifiers. Private members of the base class are not accessible in the derived class. Protected members are accessible within the derived class but not from outside.

Sealed Classes

Use the 'sealed' keyword to prevent a class from being inherited:


sealed class FinalClass
{
    // This class cannot be inherited
}
    

Best Practices

  • Use inheritance to model "is-a" relationships.
  • Keep the inheritance hierarchy shallow to maintain simplicity.
  • Override the ToString() method for meaningful string representations.
  • Use Abstract Classes for common base functionality.
  • Consider using Interfaces for multiple inheritance-like behavior.

Related Concepts

Inheritance is closely related to other OOP concepts in C#:

  • Polymorphism: Allows objects of different types to be treated as objects of a common base type.
  • Encapsulation: Helps in hiding implementation details while exposing only necessary functionalities.
  • Classes and Objects: The building blocks of OOP in C#.

Understanding inheritance is crucial for designing robust and flexible C# applications. It forms the foundation for creating reusable and maintainable code structures.