Inheritance In C#

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called the derived class) to inherit the properties and behaviors of another class (called the base class). Inheritance allows the derived class to reuse, extend, and modify the properties and behaviors of the base class, allowing for more efficient and modular code.

Here is an example of how inheritance is used in C#:

// Define the base class
public class Animal
{
    public string Name { get; set; }
    public int Age { get; set; }

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

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

// Define the derived class
public class Cat : Animal
{
    // The Cat class inherits the Name and Age properties and the Eat and Sleep methods from the Animal class

    // Define a new method specific to the Cat class
    public void Purr()
    {
        Console.WriteLine("Meow...");
    }
}

//Defined an another Derived class

public class Dog: Animal
{
    // The Dag class also inherits the Name and Age properties and the Eat and Sleep methods from the Animal class

    // Define a new method specific to the Dog class
    public void Bark()
    {
        Console.WriteLine("Barking...");
    }
}

In this example, the Cat & Dog class is derived from the Animal class, and therefore inherits all of its properties and behaviors. The Cat & Dog class also defines a new method, Purr & Barking which is specific to the derived class.

You could then define derived classes for specific types of animals, such as Cat, Tiger, and Lion, that inherit the properties and behaviors of the Animal class, and add any additional properties and behaviors that are specific to that type of animal. For example, the Cat class could include a Purr method, and the Lion class could include a Roar method.

Final Thoughts

Inheritance is a powerful concept that allows for code reuse, modularity, and extensibility in object-oriented programming. It is an important concept in OOPS. This hierarchy of classes allows for code reuse and modularity, as the common properties and behaviors of all animals are defined in the base Animal class, and can be inherited and shared by the derived classes. It also allows for extensibility, as new types of animals can be easily added to the hierarchy by defining new derived classes.