Sobes.tech
Junior — Middle

Explain the concept of virtual methods in C# and their role in implementing polymorphism.

sobes.tech AI

Answer from AI

In C#, virtual methods are methods declared with the keyword virtual, which can be overridden in derived classes using override. This forms the basis for implementing polymorphism — the ability to call methods of derived classes through references to the base class.

When a method is declared virtual, the method call is determined at runtime (dynamic binding), not at compile time. This allows an object to behave differently depending on its actual type.

Example:

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

class Dog : Animal {
    public override void Speak() {
        Console.WriteLine("Bark bark");
    }
}

Animal a = new Dog();
a.Speak(); // Outputs "Bark bark"

Here, although the variable a has the type Animal, the overridden Speak() method of the Dog class is called thanks to the virtual method.

Explain the concept of virtual methods in C# and… - sobes.tech