What is virtual keyword in C#: Explanation and Example
virtual keyword allows a method or property in a base class to be overridden in a derived class. It enables polymorphism by letting derived classes provide their own implementation while keeping a common interface.How It Works
Think of the virtual keyword as a way to say, "This method can be changed later." When you mark a method as virtual in a base class, you allow any class that inherits from it to replace that method with its own version. This is like having a recipe that you share, but your friend can tweak it to their taste.
When you call a virtual method on an object, C# checks the actual type of the object at runtime and runs the most specific version of that method. This behavior is called polymorphism, and it helps programs be flexible and easier to extend.
Example
This example shows a base class with a virtual method and a derived class that overrides it to provide a different message.
using System; class Animal { public virtual void Speak() { Console.WriteLine("The animal makes a sound."); } } class Dog : Animal { public override void Speak() { Console.WriteLine("The dog barks."); } } class Program { static void Main() { Animal myAnimal = new Animal(); Animal myDog = new Dog(); myAnimal.Speak(); // Calls base method myDog.Speak(); // Calls overridden method } }
When to Use
Use the virtual keyword when you want to allow derived classes to change or extend the behavior of a method or property. This is useful in situations where you have a general base class but expect specific versions to behave differently.
For example, in a game, you might have a base class Character with a virtual method Attack(). Different character types like Wizard or Warrior can override Attack() to perform unique actions.
Key Points
- virtual marks a method or property as overridable.
- Derived classes use
overrideto provide new behavior. - Enables polymorphism for flexible and reusable code.
- Only instance methods and properties can be virtual, not static.