Inheritance and Polymorphism in C#

January 5, 2024

This post explores the concepts of inheritance and polymorphism in C#. It explains how these features allow for code reuse and flexibility in OOP, and provides examples of how to implement them in your code.

Inheritance in C#

Inheritance is a key concept in object-oriented programming that allows a class to inherit properties and behavior from another class. In C#, you can create a new class that is based on an existing class, known as the base class. The new class, called the derived class, inherits all the members of the base class, such as fields, properties, and methods. This promotes code reuse and helps in creating a hierarchy of classes.


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

public class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("The dog is barking.");
    }
}

Polymorphism in C#

Polymorphism, another important OOP concept, allows objects of different classes to be treated as objects of a common base class. In C#, polymorphism is achieved through method overriding and method overloading. Method overriding allows a derived class to provide a specific implementation of a method that is already defined in its base class, while method overloading enables a class to have multiple methods with the same name but different parameters.


public class Shape
{
    public virtual void Draw()
    {
        Console.WriteLine("Drawing a shape.");
    }
}

public class Circle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing a circle.");
    }
}

Understanding inheritance and polymorphism is crucial for building robust and maintainable C# applications. By leveraging these features, you can create more flexible and scalable code that adapts to changing requirements.