In inheritance if we need to extend or re-write the base class function into derived class then we use virtual and override. Base class method, which we want to extend in derived class, declared as a virtual. In derived class, we override the method, which we declared virtual in base class.

Example of Virtual and Override

In the following example, we have created Abc class which is our base class and Pqr Class which is our derived class. In the base class Abc we have declared data function as a virtual function and override it into derived class.



		
public class Abc
{
    public virtual int data(int x, int y)
    {
        return (x + y);
    }
}
  public class Pqr: Abc
{
    public override int data(int x, int y)
    {
        return (x + y) * 2;
    }
}


Now when we create the object of Pqr class and call the data function it would call the override function of derived class.

		
Pqr pq = new Pqr();

Response.Write( pq.data(4, 5));

It will show the following output:-


		Virtual and Override

		Figure 1
		
		

Note: - It is very important to know that it is mandatory to declare base class function as a virtual to override it in derived class.