DEV Community

Cover image for Virtual and Override Keyword in C#
LetsUpdateSkills
LetsUpdateSkills

Posted on

1

Virtual and Override Keyword in C#

In C#, the virtual and override keywords are used to implement runtime polymorphism, allowing derived classes to provide specific implementations for methods defined in a base class. Here's an in-depth explanation of these keywords:

Virtual Keyword

The virtual keyword is used in a base class to indicate that a method, property, event, or indexer can be overridden in any derived class. When a method is marked as virtual, it means that the method has a default implementation in the base class, but derived classes can provide their own specific implementation.

Example

public class Animal
{
    // Virtual method
    public virtual void MakeSound()
    {
        Console.WriteLine("Animal makes a sound");
    }
}

Enter fullscreen mode Exit fullscreen mode

Override Keyword

The override keyword is used in a derived class to indicate that a method, property, event, or indexer is intended to override a member in the base class. The override keyword ensures that the method in the derived class has the same signature as the method in the base class and provides a new implementation for the base class's virtual method.

Example

public class Dog : Animal
{
    // Override method
    public override void MakeSound()
    {
        Console.WriteLine("Dog barks");
    }
}

Enter fullscreen mode Exit fullscreen mode

Detailed Example

Let's create a more detailed example to illustrate how virtual and override work together:

Base Class with Virtual Method

Click here to see complete tutorial

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs