What is Virtual Method in C#?

In C#, a virtual method is a method that is declared in a base class and can be overridden in derived classes. It allows derived classes to provide their own implementation of the method while preserving the polymorphic behavior.

Here are some key points about virtual methods in C#:

  1. Declaration:
    • Virtual methods are declared using the virtual keyword in the base class.
    • The virtual keyword indicates that the method can be overridden in derived classes.
  2. Method Overriding:
    • Derived classes can override a virtual method by using the override keyword in the derived class.
    • The overriding method in the derived class must have the same signature (name, return type, and parameters) as the virtual method in the base class.
  3. Polymorphism:
    • Virtual methods enable polymorphism, which means that the appropriate method implementation is determined at runtime based on the actual object type.
    • When a virtual method is called on a base class reference pointing to a derived class object, the overridden method in the derived class is invoked.
  4. Base Class Execution:
    • When a derived class overrides a virtual method, it can still call the base class implementation using the base keyword.
    • This allows the derived class to extend or modify the behavior of the base class method while reusing the base class logic.

Example usage of virtual method:

public class Shape
{
    public virtual void Draw()
    {
        Console.WriteLine("Drawing a shape.");
    }
}

public class Circle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing a circle.");
    }
}

public class Rectangle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing a rectangle.");
    }
}

Shape shape1 = new Circle();
shape1.Draw();  // Output: "Drawing a circle."

Shape shape2 = new Rectangle();
shape2.Draw();  // Output: "Drawing a rectangle."

In this example, the Shape class declares a virtual method Draw(). The Circle and Rectangle classes inherit from Shape and override the Draw() method with their own implementations.

When Draw() is called on a Shape reference pointing to a Circle object, the overridden Draw() method in Circle is invoked, resulting in the output “Drawing a circle.” Similarly, when Draw() is called on a Shape reference pointing to a Rectangle object, the overridden Draw() method in Rectangle is invoked, resulting in the output “Drawing a rectangle.”

Virtual methods provide a way to achieve polymorphism and allow derived classes to customize and extend the behavior of base class methods. They are commonly used in scenarios where different derived classes need to provide their own implementation of a specific method while adhering to a common interface or behavior defined in the base class.

error: Content is protected !!