DEV Community

Nick
Nick

Posted on

Virtual Method in C#

C# Virtual Method in C# with Code

In C#, a virtual method is a method that can be overridden in a derived class. It allows for runtime polymorphism, which means that the appropriate method implementation will be determined at runtime based on the actual type of the object.

To declare a virtual method in C#, you need to use the virtual keyword in the method signature. Here's an example:

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");
    }
}

public class Program
{
    public static void Main()
    {
        Shape shape = new Circle();
        shape.Draw(); // Output: Drawing a circle

        shape = new Rectangle();
        shape.Draw(); // Output: Drawing a rectangle
    }
}
Enter fullscreen mode Exit fullscreen mode

In the above code, we have a base class called Shape with a virtual method Draw(). We also have two derived classes Circle and Rectangle that inherit from the Shape class and override the Draw() method with their own implementations.

In the Main() method of the Program class, we create an instance of the Circle class and assign it to the base class reference variable shape. When we call the Draw() method on the shape object, it executes the overridden Draw() method in the Circle class, which outputs "Drawing a circle" to the console.

Similarly, we create an instance of the Rectangle class and assign it to the shape variable. When we call the Draw() method again, it executes the overridden Draw() method in the Rectangle class, which outputs "Drawing a rectangle" to the console.

The use of virtual methods in C# allows for flexibility in handling different types of objects through a common interface. It enables polymorphism and helps in achieving code reusability by providing an extensible design pattern.

Top comments (0)