Understanding the 'override' Keyword in C#

C# override Keyword

The override keyword is used to indicate that a method in a derived class is intended to override a method with the same signature in its base class. When a method is overridden, it allows the derived class to provide its own implementation of the method, effectively replacing the base class's implementation.

The syntax for using the override keyword:

class BaseClass
{
    public virtual void SomeMethod()
    {
        // Base class method implementation.
    }
}

class DerivedClass : BaseClass
{
    public override void SomeMethod()
    {
        // Derived class method implementation, overriding the base class method.
    }
}

In this example, the DerivedClass inherits from BaseClass and overrides the SomeMethod method. The BaseClass method is marked as virtual, and the DerivedClass method is marked as override. This indicates that the DerivedClass version of SomeMethod should be used instead of the BaseClass version whenever a DerivedClass object calls this method.

It's important to note the following points regarding the override keyword:

  1. The method being overridden in the base class must be declared as virtual, abstract, or part of an interface. This indicates that the method can be overridden in derived classes.

  2. The signature (method name, return type, and parameters) of the overriding method in the derived class must exactly match the signature of the virtual or abstract method in the base class.

  3. The override keyword must be used explicitly to indicate that you are intentionally overriding a base class method. If the method signature in the derived class does not match any virtual or abstract method in the base class, the C# compiler will raise an error.

Here's an example of using override:

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

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

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

// Usage example:
Shape shape1 = new Circle();
Shape shape2 = new Square();

shape1.Draw(); // Output: "Drawing a circle."
shape2.Draw(); // Output: "Drawing a square."

In this example, the Circle and Square classes both derive from the Shape class and override the Draw method. When calling the Draw method on objects of Circle and Square, the overridden versions in the derived classes are executed.

The override keyword is essential in object-oriented programming as it enables polymorphism and allows classes to provide custom behavior while still adhering to a common interface defined in their base classes.