The virtual keyword in C# is used to allow a method, property, or event in a base class to be overridden in a derived class. A virtual member does not have to be overridden, but if it is, the overridden version in the subclass will be executed at runtime, enabling polymorphic behavior.
✅Example of virtual Keyword in a class:
class Animal
{
public virtual void MakeSound() // virtual method
{
Console.WriteLine(“Some generic animal sound”);
}
}
class Dog : Animal
{
public override void MakeSound() // override in derived class
{
Console.WriteLine(“Bark”);
}
}
Usage:
Animal a = new Dog();
a.MakeSound(); // Output: Bark
Explanation:
- The
MakeSoundmethod inAnimalis marked asvirtual. - The
Dogclass overrides it using theoverridekeyword. - When calling
MakeSoundon anAnimalreference holding aDogobject, the overriddenDogmethod executes at runtime.