Understanding Virtual and Abstract Methods in C#

By FoxLearn 1/2/2025 8:09:29 AM   85
In C#, abstract methods and virtual methods both serve important roles, but they differ in their behavior and use cases.

Virtual Methods

A virtual method in C# is defined using the virtual keyword in the base class. It may or may not have an implementation. Subclasses can override these methods, providing their own versions of the method. This enables runtime polymorphism, where the actual method invoked is determined at runtime based on the object's type, not the reference type.

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

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

class Program
{
    static void Main()
    {
        Animal animal = new Animal();
        animal.Speak(); // Outputs: The animal makes a sound

        Animal dog = new Dog();
        dog.Speak(); // Outputs: The dog barks
    }
}

In this example, the Speak() method is declared as virtual in the Animal class and overridden in the Dog class. When a method is called on an Animal reference that points to a Dog object, the overridden method in the Dog class is invoked.

Abstract Methods

Abstract methods, in contrast, are methods declared without any implementation in the base class and marked with the abstract keyword. These methods force subclasses to provide an implementation. The abstract method is declared in an abstract class, and any non-abstract subclass must implement the method. If the subclass does not provide an implementation, a compile-time error will occur.

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

public class Circle : Shape
{
    public double Radius { get; set; }

    public override double CalculateArea()
    {
        return Math.PI * Radius * Radius;
    }
}

class Program
{
    static void Main()
    {
        Shape shape = new Circle { Radius = 5 };
        Console.WriteLine("Area of circle: " + shape.CalculateArea());
    }
}

In this example, CalculateArea() is an abstract method in the Shape class. The Circle class must override this method and provide its own implementation to calculate the area of the circle.