C# - Inheritance


Inheritance in C# refers to a class's capacity to inherit properties, methods, and other members from another  class.

The class being inherited from is referred to as the base class or parent class, and the class inheriting from it is  referred to as the derived class or child class.

One of the most important concepts in object-oriented programming is inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and speeds up implementation time.

When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.

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

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

In this example, the Animal class is the base class, and the Dog class is the derived class that inherits from Animal. The Dog class can access the Eat() method from the Animal class without explicitly defining it because it inherits it. Additionally, the Dog class has its own method Bark().

You can create an instance of the Dog class and use both inherited and defined methods:

Dog myDog = new Dog(); 
myDog.Eat(); // This calls the Eat() method from the Animal class 
myDog.Bark(); // This calls the Bark() method from the Dog class

Mutiple Inheritance

In C#, a class cannot directly inherit from multiple classes, which is known as multiple inheritance. Unlike some other programming languages (like C++), C# does not support this feature for classes to inherit from more than one class.

However, C# does allow a form of multiple inheritance through interfaces. An interface in C# defines a contract that a class can implement. A class can implement multiple interfaces, thereby inheriting the method signatures defined within those interfaces. This is a way to achieve some level of multiple inheritance in C#.

// Interface 1 
public interface IDrawable 
{ 
    void Draw(); 
} 

// Interface 2 
public interface IResizable 
{ 
    void Resize(); 
} 

// Class implementing multiple interfaces 
public class Shape : IDrawable, IResizable 
{
    public void Draw() 
    { 
        Console.WriteLine("Drawing the shape..."); 
    } 
    
    public void Resize() 
    { 
        Console.WriteLine("Resizing the shape..."); 
    } 
}