0
0
CsharpConceptBeginner · 3 min read

What is virtual keyword in C#: Explanation and Example

In C#, the 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.

csharp
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
    }
}
Output
The animal makes a sound. The dog barks.
🎯

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 override to provide new behavior.
  • Enables polymorphism for flexible and reusable code.
  • Only instance methods and properties can be virtual, not static.

Key Takeaways

The virtual keyword allows methods to be overridden in derived classes for flexible behavior.
Use virtual when you want to provide a default implementation that can be changed later.
Derived classes override virtual methods using the override keyword.
Virtual methods enable polymorphism by calling the most specific method at runtime.