C# Method Overriding

Introduction

Method overriding is a feature in C# that allows a derived class to provide a specific implementation of a method that is already defined in its base class. Method overriding is a key aspect of runtime polymorphism, enabling dynamic method invocation. The base class method must be marked with the virtual keyword, and the derived class method must use the override keyword.

How Method Overriding Works

  • Base Class: The class whose method is overridden.
  • Derived Class: The class that overrides the method of the base class.

Syntax

public class BaseClass
{
    public virtual void MethodName()
    {
        // Base class implementation
    }
}

public class DerivedClass : BaseClass
{
    public override void MethodName()
    {
        // Derived class implementation
    }
}

Example

Let’s consider an example where we have a base class Animal and a derived class Dog that overrides the MakeSound method.

using System;

namespace MethodOverridingExample
{
    public class Animal
    {
        // Virtual method in the base class
        public virtual void MakeSound()
        {
            Console.WriteLine("Animal makes a sound.");
        }
    }

    public class Dog : Animal
    {
        // Override method in the derived class
        public override void MakeSound()
        {
            Console.WriteLine("Dog barks.");
        }
    }

    public class Cat : Animal
    {
        // Override method in the derived class
        public override void MakeSound()
        {
            Console.WriteLine("Cat meows.");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Animal myAnimal;

            myAnimal = new Dog();
            myAnimal.MakeSound(); // Outputs: Dog barks.

            myAnimal = new Cat();
            myAnimal.MakeSound(); // Outputs: Cat meows.
        }
    }
}

Output

Dog barks.
Cat meows.

Key Points

  1. Virtual Keyword: The method in the base class must be marked with the virtual keyword.
  2. Override Keyword: The method in the derived class must be marked with the override keyword.
  3. Same Signature: The overridden method must have the same signature (name and parameters) as the base class method.
  4. Base Keyword: The base keyword can be used to call the base class method from the derived class.

Using the base Keyword

The base keyword is used to access members of the base class from within a derived class. It is often used to call the base class constructor or methods.

Example

using System;

namespace BaseKeywordExample
{
    public class Animal
    {
        public string Name { get; set; }

        public Animal(string name)
        {
            Name = name;
        }

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

    public class Dog : Animal
    {
        public Dog(string name) : base(name)
        {
        }

        public override void MakeSound()
        {
            base.MakeSound(); // Call the base class method
            Console.WriteLine("Dog barks.");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Dog myDog = new Dog("Buddy");
            myDog.MakeSound();
        }
    }
}

Output

Animal makes a sound.
Dog barks.

Benefits of Method Overriding

  1. Runtime Polymorphism: Method overriding enables runtime polymorphism, allowing dynamic method invocation based on the object type.
  2. Code Reusability: Derived classes can reuse the base class method implementation using the base keyword, reducing code duplication.
  3. Extensibility: Method overriding allows extending or modifying the behavior of base class methods in derived classes without changing the base class code.

Example: Shape Hierarchy

Let’s consider a more complex example with a shape hierarchy.

using System;

namespace ShapeExample
{
    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.");
        }
    }

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

    class Program
    {
        static void Main(string[] args)
        {
            Shape myShape;

            myShape = new Circle();
            myShape.Draw(); // Outputs: Drawing a circle.

            myShape = new Rectangle();
            myShape.Draw(); // Outputs: Drawing a rectangle.
        }
    }
}

Output

Drawing a circle.
Drawing a rectangle.

Example: Bank Account Hierarchy

Let’s consider another example with a bank account hierarchy.

using System;

namespace BankAccountExample
{
    public class BankAccount
    {
        public virtual void CalculateInterest()
        {
            Console.WriteLine("Calculating interest for a bank account.");
        }
    }

    public class SavingsAccount : BankAccount
    {
        public override void CalculateInterest()
        {
            Console.WriteLine("Calculating interest for a savings account.");
        }
    }

    public class CheckingAccount : BankAccount
    {
        public override void CalculateInterest()
        {
            Console.WriteLine("Calculating interest for a checking account.");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            BankAccount myAccount;

            myAccount = new SavingsAccount();
            myAccount.CalculateInterest(); // Outputs: Calculating interest for a savings account.

            myAccount = new CheckingAccount();
            myAccount.CalculateInterest(); // Outputs: Calculating interest for a checking account.
        }
    }
}

Output

Calculating interest for a savings account.
Calculating interest for a checking account.

Conclusion

Method overriding in C# allows derived classes to provide specific implementations of methods defined in their base classes. By using the virtual keyword in the base class and the override keyword in the derived class, you can achieve runtime polymorphism and dynamic method invocation. Understanding method overriding is crucial for designing flexible and extensible object-oriented applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top