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

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay