A virtual method in C# language is method that have virtual keyword in its declaration. In c# inheritance feature, we may want to allow derived classes to have their own implementation for some of the methods resides into a base class.

For this purpose, we use virtual keyword in method declaration in base class, so, that derive class can override it and implement its own feature.

In below c# code example, we have “Printer” base class that have two method print() and display(). print()method does printing and display() function will have display unit of dimension of 5×5 units.

Here, we want to have a derived class “LaserJet” printer that will use the print() method of base class, but, will have display unit of 10×10.

So, we will declare base class display() method as virtual and override it into derived class and implement new dimension of 10×10.

class Printer
    {
        //common print function that all derived classes will use
        //the same feature.
        //Not making it virtual as all derived classes will call this.
        public void print()
        {
            Console.WriteLine("Printer Printing...");
        }

        //Making virtual, so, derived classes can implement thier
        //own feature.
        public virtual void display()
        {
            Console.WriteLine("Printer Display dimention: 5x5\n");
        }


    }
    class LaserJet : Printer
    {

        public override void display()
        {
            Console.WriteLine("LaserJet Display dimention: 10x10");
        }

    }


    //------------TEST-----------
    
        class Program
        {
            static void Main(string[] args)
            {
                //Base class object
                Printer p = new Printer();
                p.print();//print
                p.display();

                //Derived class behaviour
                Printer lp = new LaserJet();
                lp.print();//use base class print() method

                // will use its(LaserJet) own display() method implementation.
                lp.display();

            }
        }

Output:
Printer Printing…
Printer Display dimention: 5×5

Printer Printing…
LaserJet Display dimention: 10×10

NOTES:

Virtual keyword is different from “abstract” as virtual keyword does not force derived class to implement it, but, abstract forces derived classes to implement it.

Related Posts