Junior
What is a virtual method in C#?
sobes.tech AI
Answer from AI
A virtual method in C# is a method declared with the virtual keyword in a base class, which can be overridden in derived classes using the override keyword. This allows for polymorphism, where the method call depends on the actual type of the object at runtime, rather than the type of the variable.
Example:
class Animal
{
public virtual void Speak()
{
Console.WriteLine("Animal makes a sound");
}
}
class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Woof");
}
}
Animal a = new Dog();
a.Speak(); // Outputs "Woof" thanks to the virtual method
Without virtual and override, the method call would be static and would not consider the actual object type at runtime.