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 Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay