Sobes.tech
Junior — Middle

Selgitage virtuaalsete meetodite kontseptsiooni C# keeles ja nende rolli polümorfismi rakendamises.

sobes.tech AI

Vastus AI-lt

In C#, virtual methods are methods declared with the virtual keyword, which can be overridden in derived classes using override. This is 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 call to the method 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("Woof woof");
    }
}

Animal a = new Dog();
a.Speak(); // Prints "Woof woof"

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