C# Method Overriding

In C#, method overriding is a feature that allows a derived class to provide a different implementation of a method that is already defined in its base class. Method overriding is an essential part of achieving polymorphism in object-oriented programming.

To override a method in C#, you need to follow these rules:

  1. The base class (or the class being inherited) must declare the method with the virtual keyword. This indicates that the method can be overridden by derived classes.
  2. The derived class must declare the overriding method using the override keyword. The method signature, including the name, return type, and parameters, must match the base class method exactly.

Here’s an example that demonstrates method overriding in C#:

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

class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Dog barks.");
    }
}

class Cat : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Cat meows.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Animal animal = new Animal();
        animal.MakeSound();  // Output: "Animal makes a sound."

        Animal dog = new Dog();
        dog.MakeSound();     // Output: "Dog barks."

        Animal cat = new Cat();
        cat.MakeSound();     // Output: "Cat meows."
    }
}

In the example above, the Animal class defines the MakeSound method as virtual. The Dog and Cat classes inherit from Animal and override the MakeSound method with their own implementations using the override keyword.

When you create instances of the derived classes (Dog and Cat) but store them in variables of the base class type (Animal), the overridden method in each derived class is called when you invoke MakeSound(). This is known as dynamic polymorphism, where the method implementation is determined at runtime based on the actual type of the object.