C# Inheritance

Inheritance is one of the fundamental concepts of Object-Oriented Programming (OOP) that allows a class to inherit the properties and behaviours (methods) from another class. In C#, inheritance enables code reuse, hierarchical classification, and the ability to extend the functionality.

In simple terms, think of inheritance like a family tree for classes in programming. Just like how children inherit traits from their parents, in C# one class can inherit features from another class. Let me break this down:

What is Inheritance?

  • It's like creating a new class that automatically gets all the good stuff from an existing class
  • The original class is called the "parent" or "base" class
  • The new class that inherits is called the "child" or "derived" class

Types of Inheritance in C#:

  1. Single Inheritance: A class can inherit from only one base class.

  2. Multilevel Inheritance: A class can inherit from a derived class.

  3. Hierarchical Inheritance: Multiple classes inherit from a single base class.

  4. Interface Inheritance: A class can implement one or more interfaces.

Example 1 : Single Inheritance:


using System;

class Animal
{
    public string Name { get; set; }

    public void Eat()
    {
        Console.WriteLine("Eating...");
    }

    public void Sleep()
    {
        Console.WriteLine("Sleeping...");
    }
}

class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("Woof...");
    }
}

class Program
{
    static void Main()
    {
        Dog myDog = new Dog();
        myDog.Name = "Buddy";
        Console.WriteLine("Dog's name: " + myDog.Name);
        
        myDog.Eat(); // Inherited method
        myDog.Sleep(); // Inherited method
        myDog.Bark(); // Method specific to Dog
    }
}

The cool thing is that myDog object can do everything an Animal can do (like eat and have a name), plus its own special thing (bark)!

Output:


Dog's name: Buddy
Eating...
Sleeping...
Woof...

Explanation:

  • Dog is a derived class that inherits from the base class Animal.

  • The Dog class can access the Eat() and Sleep() methods because they are inherited from Animal.

  • The Bark() method is specific to Dog.