C# - Virtual Method

Virtual Method

The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class.

When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.

By default, methods are non-virtual. You cannot override a non-virtual method.

You cannot use the virtual modifier with the static, abstract, private, or override modifiers. The following example shows a virtual property:

Virtual Method Example in C#

using System;
namespace MethodOverridingUsingVirtualMethodApp
{
    class shape
    {
        public virtual void draw()
        {
            Console.WriteLine("Shape Drawing...");
        }
        
    }
    class circle : shape
    {
        public override void draw()
        {
            Console.WriteLine("Circle Drawing...");
        }
    }
    class rect : shape
    {
        public override void draw()
        {
            Console.WriteLine("rect Drawing...");
        }
    }
    class triangle : shape
    {
        public override void draw()
        {
            Console.WriteLine("triangle Drawing...");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
           
            shape r;
            shape s = new shape();
            circle c = new circle();
            rect rt = new rect();
            r = s;
            r.draw();
            r = c;
            r.draw();
            r = rt;
            r.draw();
            r = new triangle();
            r.draw();
            shape[] r_arr = new shape[5];
            r_arr[0] = new circle();
            r_arr[1] = new triangle();
            r_arr[2] = new circle();
            r_arr[3] = new rect();
            r_arr[4] = new triangle();
            Console.WriteLine("Drawing Shapes using array of References");
            for (int i = 0; i < 5; i++)
                r_arr[i].draw();
        }
    }
}

Output - Virtual Method Example in C#

Shape Drawing...
Circle Drawing...
rect Drawing...
triangle Drawing...
Drawing Shapes using array of References
Circle Drawing...
triangle Drawing...
Circle Drawing...
rect Drawing...
triangle Drawing...