C# - Virtual and Override Keyword

Virtual and Override Keyword in C#

Introduction to Virtual and Override Keywords in C#

C# is a powerful object-oriented programming language developed by Microsoft as part of the .NET ecosystem. One of the most important features of object-oriented programming (OOP) is polymorphism. In C#, polymorphism is primarily achieved using the virtual and override keywords. These keywords allow derived classes to provide specific implementations of methods that are already defined in a base class.

Understanding the C# virtual keyword and C# override keyword is essential for mastering runtime polymorphism in C#, designing extensible applications, and writing maintainable enterprise-level code. In this detailed tutorial, we will explore how virtual and override work, how method overriding differs from method hiding, practical examples, best practices, and real-world use cases.

Understanding Polymorphism in C#

What is Polymorphism?

Polymorphism means β€œmany forms.” In C#, polymorphism allows objects of different classes to be treated as objects of a common base class. There are two types of polymorphism:

  • Compile-time polymorphism (Method Overloading)
  • Runtime polymorphism (Method Overriding)

The virtual and override keywords in C# are used to achieve runtime polymorphism. Runtime polymorphism allows a method call to be resolved at runtime rather than compile time.

What is the Virtual Keyword in C#?

Definition of Virtual Keyword

The virtual keyword in C# is used to declare a method, property, indexer, or event in a base class that can be overridden in a derived class.

When a method is marked as virtual, it allows derived classes to provide a different implementation of that method.

Syntax of Virtual Method


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

Here, the MakeSound() method is marked as virtual. This means child classes can override it.

Key Points About Virtual Keyword

  • Declared in base class.
  • Must be public, protected, or internal.
  • Cannot be private.
  • Enables runtime method dispatch.
  • Supports runtime polymorphism in C#.

What is the Override Keyword in C#?

Definition of Override Keyword

The override keyword in C# is used in a derived class to provide a new implementation of a virtual method defined in the base class.

Syntax of Override Method


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

Here, the Dog class overrides the virtual method from the Animal class.

Important Rules for Override

  • Base method must be marked as virtual, abstract, or override.
  • Method signature must match exactly.
  • Access modifier cannot be changed.
  • Override methods are implicitly virtual.

Complete Example of Virtual and Override in C#

Let us see a full example demonstrating method overriding in C#.


using System;

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

public class Cat : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Cat meows.");
    }
}

public class Program
{
    public static void Main()
    {
        Animal myAnimal = new Cat();
        myAnimal.MakeSound();
    }
}

Output:


Cat meows.

Even though the reference type is Animal, the runtime object is Cat. Therefore, the overridden method is called. This demonstrates runtime polymorphism in C#.

Virtual vs Override Keyword in C#

Virtual Override
Declared in base class Declared in derived class
Allows method to be overridden Provides new implementation
Enables polymorphism Implements polymorphism
Optional in base class Mandatory in derived class when overriding

Method Overriding vs Method Hiding in C#

Method Overriding

  • Uses virtual and override keywords.
  • Runtime polymorphism.
  • Resolved at runtime.

Method Hiding

Method hiding uses the new keyword.


public class Animal
{
    public void MakeSound()
    {
        Console.WriteLine("Animal sound.");
    }
}

public class Dog : Animal
{
    public new void MakeSound()
    {
        Console.WriteLine("Dog bark.");
    }
}

Method hiding does not support runtime polymorphism. It resolves at compile time.

Calling Base Class Method Using base Keyword

Sometimes you may want to call the base class implementation inside an overridden method.


public class Dog : Animal
{
    public override void MakeSound()
    {
        base.MakeSound();
        Console.WriteLine("Dog barks loudly.");
    }
}

The base keyword allows access to base class members.

Virtual Properties in C#

Not only methods, but properties can also be virtual.


public class Shape
{
    public virtual double Area
    {
        get { return 0; }
    }
}

public class Circle : Shape
{
    private double radius;

    public Circle(double r)
    {
        radius = r;
    }

    public override double Area
    {
        get { return 3.14 * radius * radius; }
    }
}

Sealed Override in C#

If you want to prevent further overriding in derived classes, use sealed override.


public class Dog : Animal
{
    public sealed override void MakeSound()
    {
        Console.WriteLine("Dog bark.");
    }
}

Now no further derived class can override this method.

Abstract vs Virtual in C#

Abstract Method

  • No implementation in base class.
  • Must be overridden.

Virtual Method

  • Has default implementation.
  • Overriding is optional.

Real-World Use Cases of Virtual and Override

1. Payment Processing System

A base Payment class can define a virtual method ProcessPayment(). Different payment methods override it.

2. Logging Framework

Base logger class defines virtual Log(). Derived classes customize logging behavior.

3. Game Development

Base Character class defines virtual Attack(). Different characters override it.

Common Interview Questions on Virtual and Override

1. What happens if virtual keyword is removed?

Derived class cannot override the method using override.

2. Can static methods be virtual?

No, static methods cannot be virtual or overridden.

3. Can constructors be virtual?

No, constructors cannot be virtual.

4. Is overriding mandatory?

No, only if method is abstract.

Performance Considerations

Virtual method calls involve dynamic dispatch. While the performance overhead is minimal in modern .NET applications, excessive use of virtual methods may slightly impact performance in highly optimized systems.


The C# virtual and override keywords are fundamental to achieving runtime polymorphism. Virtual enables a method to be overridden, while override provides a new implementation in a derived class. Together, they form the backbone of inheritance in C# and object-oriented programming in C#.

Mastering method overriding in C# allows developers to build scalable, flexible, and maintainable software applications. Whether you're preparing for a C# interview, learning .NET development, or building enterprise applications, understanding virtual and override is essential.

logo

C#

Beginner 5 Hours

Virtual and Override Keyword in C#

Introduction to Virtual and Override Keywords in C#

C# is a powerful object-oriented programming language developed by Microsoft as part of the .NET ecosystem. One of the most important features of object-oriented programming (OOP) is polymorphism. In C#, polymorphism is primarily achieved using the virtual and override keywords. These keywords allow derived classes to provide specific implementations of methods that are already defined in a base class.

Understanding the C# virtual keyword and C# override keyword is essential for mastering runtime polymorphism in C#, designing extensible applications, and writing maintainable enterprise-level code. In this detailed tutorial, we will explore how virtual and override work, how method overriding differs from method hiding, practical examples, best practices, and real-world use cases.

Understanding Polymorphism in C#

What is Polymorphism?

Polymorphism means “many forms.” In C#, polymorphism allows objects of different classes to be treated as objects of a common base class. There are two types of polymorphism:

  • Compile-time polymorphism (Method Overloading)
  • Runtime polymorphism (Method Overriding)

The virtual and override keywords in C# are used to achieve runtime polymorphism. Runtime polymorphism allows a method call to be resolved at runtime rather than compile time.

What is the Virtual Keyword in C#?

Definition of Virtual Keyword

The virtual keyword in C# is used to declare a method, property, indexer, or event in a base class that can be overridden in a derived class.

When a method is marked as virtual, it allows derived classes to provide a different implementation of that method.

Syntax of Virtual Method

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

Here, the MakeSound() method is marked as virtual. This means child classes can override it.

Key Points About Virtual Keyword

  • Declared in base class.
  • Must be public, protected, or internal.
  • Cannot be private.
  • Enables runtime method dispatch.
  • Supports runtime polymorphism in C#.

What is the Override Keyword in C#?

Definition of Override Keyword

The override keyword in C# is used in a derived class to provide a new implementation of a virtual method defined in the base class.

Syntax of Override Method

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

Here, the Dog class overrides the virtual method from the Animal class.

Important Rules for Override

  • Base method must be marked as virtual, abstract, or override.
  • Method signature must match exactly.
  • Access modifier cannot be changed.
  • Override methods are implicitly virtual.

Complete Example of Virtual and Override in C#

Let us see a full example demonstrating method overriding in C#.

using System; public class Animal { public virtual void MakeSound() { Console.WriteLine("Animal makes a sound."); } } public class Cat : Animal { public override void MakeSound() { Console.WriteLine("Cat meows."); } } public class Program { public static void Main() { Animal myAnimal = new Cat(); myAnimal.MakeSound(); } }

Output:

Cat meows.

Even though the reference type is Animal, the runtime object is Cat. Therefore, the overridden method is called. This demonstrates runtime polymorphism in C#.

Virtual vs Override Keyword in C#

Virtual Override
Declared in base class Declared in derived class
Allows method to be overridden Provides new implementation
Enables polymorphism Implements polymorphism
Optional in base class Mandatory in derived class when overriding

Method Overriding vs Method Hiding in C#

Method Overriding

  • Uses virtual and override keywords.
  • Runtime polymorphism.
  • Resolved at runtime.

Method Hiding

Method hiding uses the new keyword.

public class Animal { public void MakeSound() { Console.WriteLine("Animal sound."); } } public class Dog : Animal { public new void MakeSound() { Console.WriteLine("Dog bark."); } }

Method hiding does not support runtime polymorphism. It resolves at compile time.

Calling Base Class Method Using base Keyword

Sometimes you may want to call the base class implementation inside an overridden method.

public class Dog : Animal { public override void MakeSound() { base.MakeSound(); Console.WriteLine("Dog barks loudly."); } }

The base keyword allows access to base class members.

Virtual Properties in C#

Not only methods, but properties can also be virtual.

public class Shape { public virtual double Area { get { return 0; } } } public class Circle : Shape { private double radius; public Circle(double r) { radius = r; } public override double Area { get { return 3.14 * radius * radius; } } }

Sealed Override in C#

If you want to prevent further overriding in derived classes, use sealed override.

public class Dog : Animal { public sealed override void MakeSound() { Console.WriteLine("Dog bark."); } }

Now no further derived class can override this method.

Abstract vs Virtual in C#

Abstract Method

  • No implementation in base class.
  • Must be overridden.

Virtual Method

  • Has default implementation.
  • Overriding is optional.

Real-World Use Cases of Virtual and Override

1. Payment Processing System

A base Payment class can define a virtual method ProcessPayment(). Different payment methods override it.

2. Logging Framework

Base logger class defines virtual Log(). Derived classes customize logging behavior.

3. Game Development

Base Character class defines virtual Attack(). Different characters override it.

Common Interview Questions on Virtual and Override

1. What happens if virtual keyword is removed?

Derived class cannot override the method using override.

2. Can static methods be virtual?

No, static methods cannot be virtual or overridden.

3. Can constructors be virtual?

No, constructors cannot be virtual.

4. Is overriding mandatory?

No, only if method is abstract.

Performance Considerations

Virtual method calls involve dynamic dispatch. While the performance overhead is minimal in modern .NET applications, excessive use of virtual methods may slightly impact performance in highly optimized systems.


The C# virtual and override keywords are fundamental to achieving runtime polymorphism. Virtual enables a method to be overridden, while override provides a new implementation in a derived class. Together, they form the backbone of inheritance in C# and object-oriented programming in C#.

Mastering method overriding in C# allows developers to build scalable, flexible, and maintainable software applications. Whether you're preparing for a C# interview, learning .NET development, or building enterprise applications, understanding virtual and override is essential.

Related Tutorials

Frequently Asked Questions for C#

C# is much easier to learn than C++. C# is a simpler, high-level-of-abstraction language, while C++ is a low-level language with a higher learning curve.

C# outshines Python when it comes to runtime performance. As a compiled language, C# code is converted to machine code, which can be executed more efficiently by the processor. This results in faster execution times and better performance, especially in resource-intensive tasks.

Python and JavaScript programmers also earn high salaries, ranking #3 and #4 in compensation. 
C# is the highest-paid programming language but has less demand than Python, JavaScript, and Java.

No. Microsoft has invested substantially in ensuring that C# is the dominant language today, spending two billion dollars on marketing and attempting to convince developers to embrace this new platform, which is also based on the.NET foundation.

C# is primarily used on the Windows .NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.


You can’t be able to become Master of C# in 3 months since it has many concepts to learn and implement. NOTE: no one can become master in particular programming language. Everyday they introducing new concepts we need to get practice on it which practically somewhat tough.

C-Sharp is one of the most widely used languages for creating system backend.It's because of its incredible features, such as Windows server automation. Apart from that, it's fantastic because it runs codes quite quickly. It can also be used to create CLI applications and game creation.

Easy to learn and use: C# is simpler than Java due to its use of fewer keywords and usually shorter lines of code. Hence, it is easier to learn to code in C# compared to Java. Flexible Data Types: C# provides more flexibility in defining data types than Java.

Four steps of code compilation in C# include : 
  • Source code compilation in managed code.
  • Newly created code is clubbed with assembly code.
  • The Common Language Runtime (CLR) is loaded.
  • Assembly execution is done through CLR.

The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.


The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.


Among other languages, C# is gaining huge popularity for developing web-based applications. Its core concepts help build an interactive environment and provide functionalities that the dynamic web platform requires. Most aspiring full-stack developers choose this versatile language.

The C# programming language was designed by Anders Hejlsberg from Microsoft in 2000 and was later approved as an international standard by Ecma (ECMA-334) in 2002 and ISO/IEC (ISO/IEC 23270 and 20619) in 2003. Microsoft introduced C# along with .NET Framework and Visual Studio, both of which were closed-source. 

C# outshines Python when it comes to runtime performance. As a compiled language, C# code is converted to machine code, which can be executed more efficiently by the processor. This results in faster execution times and better performance, especially in resource-intensive tasks.

Yes, C# is used by many large organizations, start-ups and beginners alike. It takes some of the useful features of C and adds syntax to save time and effort. Although C# is based on C, you can learn it without any knowledge of C β€” in fact, this course is perfect for those with no coding experience at all!

C# is a very mature language that evolved significantly over the years.
The C# language is one of the top 5 most popular programming languages and .NET is the most loved software development framework in the world.
TIOBE Index predicts C# as 2023 'Language of the Year' close to overtake Java in popularity.

Generally, the C# language is not limited to the Windows operating system. In a sense, however, it is limited to Microsoft software. C# language "belongs" to Microsoft, it is developed by Microsoft and it is Microsoft that provides the runtime environment required for the operation of programs written in C#.

C# (pronounced "C sharp") is called so because the "#" symbol is often referred to as "sharp." The name was chosen by Microsoft when they developed the language. It's a play on words related to musical notation where "C#" represents the musical note C sharp.

Dennis MacAlistair Ritchie (September 9, 1941 – c. October 12, 2011) was an American computer scientist. He created the C programming language and, with long-time colleague Ken Thompson, the Unix operating system and B language.

C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.


line

Copyrights © 2024 letsupdateskills All rights reserved