Difference Between virtual and abstract Methods in C#

Difference Between virtual and abstract Methods in C#

In object-oriented programming with C#, both virtual and abstract methods enable polymorphism. However, they serve different purposes in class design and inheritance.



🔹 What is a virtual Method?

✅ Example:

public class Animal
{
    public virtual void Speak()
    {
        Console.WriteLine("Animal speaks");
    }
}

public class Dog : Animal
{
    public override void Speak()
    {
        Console.WriteLine("Dog barks");
    }
}
Use Case: When the base class has a common/default behavior that can optionally be overridden by derived classes.

🔸 What is an abstract Method?

✅ Example:

public abstract class Shape
{
    public abstract double GetArea();
}

public class Circle : Shape
{
    private double radius;

    public Circle(double radius)
    {
        this.radius = radius;
    }

    public override double GetArea()
    {
        return Math.PI * radius * radius;
    }
}
Use Case: When the base class defines a method signature but defers its implementation to derived classes.

📊 Comparison Table: virtual vs abstract Methods

Feature virtual Method abstract Method
Has implementation in base class? Yes No
Can be overridden in derived class? Yes (optional) Yes (mandatory)
Declared in Regular or abstract class Only abstract class
Must be overridden? No Yes
Use Case When base behavior is available but override is optional When base has no behavior and forces subclass implementation

🧠 Summary

  • Use virtual when a method in the base class has a default behavior but can be changed in a subclass.
  • Use abstract when the base class wants to enforce that all derived classes must provide their own behavior.
Tip: Both methods work hand-in-hand with polymorphism, but choose the one that best fits the need for flexibility or enforcement in design.

Comments

Popular posts from this blog

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Promises in Angular

Comprehensive Guide to C# and .NET Core OOP Concepts and Language Features