C# Overriding – virtual and override Keyword

Updated on     Kisan Patel

Overriding is a feature that allows a derived class to provide a specific implementation of a method that is already defined in a base class. The implementation of method in the derived class overrides or replaces the implementation of method in its base class.

So, When you call a method, the method defined in the derived class is invoked and executed instead of the one in the base class.

To invoke the method of a derived class that is already defined in the base class, you need to perform following steps :

  1. Declare the base class method as virtual.
  2. Implement the derived class method using the override keyword.

For Example,

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

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

Here we will override the Draw() method of the Shape class in the Circle class, so we have to mark the Draw method in the Shape (base) class as virtual and the Draw() method in the Circle (sub) class as override.

Now, write code in our Main() method as shown below.

static void Main(string[] args)
{
    Ciracle c = new Ciracle();
    c.Draw();
}

the output of the above code…

c-sharp-overriding-example


C#

Leave a Reply