Method Overriding in CSharp

Method Overriding in C#

Method overriding is a key concept in object-oriented programming and C#. It allows a derived class to provide a specific implementation of a method that is already defined in the base class. In this article, we’ll explore method overriding with code examples.

Method Overriding Basics:

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

  1. The method in the derived class must have the same name, return type, and parameters as the method in the base class.
  2. The method in the base class must be marked as virtual or abstract. This indicates that it’s intended to be overridden.

Example:

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

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

Using Method Overriding:

You can create instances of both the base and derived classes and call the MakeSound method to see the overridden behavior:

Animal animal = new Animal();
Animal dog = new Dog();

animal.MakeSound(); // Output: "Animal makes a sound"
dog.MakeSound();    // Output: "Dog barks"

In this example, the MakeSound method is overridden in the Dog class, providing a specific implementation. When you call the method on an instance of the derived class, it invokes the overridden method.

Benefits of Method Overriding:

  1. Polymorphism: Method overriding is a fundamental concept in achieving polymorphism, where objects of derived classes can be treated as objects of the base class.
  2. Code Reusability: You can reuse methods from the base class while providing specific implementations in derived classes.
  3. Flexibility: Method overriding allows you to extend and customize the behavior of base class methods.

Important Considerations:

  1. Access Modifiers: The access modifier of the overriding method cannot be more restrictive than the base method. For example, you can’t override a public method with a private method.
  2. override Keyword: The override keyword is used to indicate that a method is intended to override a base class method.

Method overriding in C# is a fundamental concept in object-oriented programming that allows you to customize and extend the behavior of base class methods in derived classes, promoting code reusability and flexibility.