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?
- A virtual method provides a default implementation in the base class.
- Derived classes may override it using the
overridekeyword. - If not overridden, the base implementation is executed.
✅ 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?
- An abstract method has no body in the base class.
- It must be defined in an
abstract class. - All derived classes must override and implement it.
✅ 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
virtualwhen a method in the base class has a default behavior but can be changed in a subclass. - Use
abstractwhen 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
Post a Comment