Holi Sale. Get upto 40% OFF on Job-oriented Training! Offer Ending in
D
H
M
S
Get Now
Browse Tutorials
Understanding virtual, override and new keyword in C#

Understanding virtual, override and new keyword in C#

11 Mar 2024
Intermediate
97.1K Views
18 min read
Learn via Video Course & by Doing Hands-on Labs

C# Programming For Beginners Free Course

C# Keywords: An Overview

The Keywords are predefined, reserved identifiers that have special meanings to the compiler. They are used as identifiers in your program with the @ prefix. In C# keywords are used in Object-oriented Programming Especially in polymorphism. But in this C# tutorial, we will understand new, override, and virtual keywords as they play a vital part in method overriding, method overloading, and method hiding.

We will specifically explore what virtual override and new keywords are in c#virtual keyword in c# with an examplethe difference between virtual override and new keyword in c#, or virtual vs override vs new keyword in c#.Before the understanding of virtual, override, and new keyword. Let's first discuss polymorphism.

What is polymorphism?

Polymorphism is made up of two words, poly means more than one and morphs means forms. Therefore, polymorphism means the ability to take more than one form. This property makes the same entities such as functions, and operators perform differently in different scenarios. Now let's implement keywords in simple inheritance.

Simple class inheritance

In this introductory part, I will explain with a demo example why we need to use new, virtual, and override keywords. Let's consider the below class hierarchy with classes A, B, and C. A is the super/base class, B is derived from class A and C is derived from class B. Also see the example of how the inheritance concept works before understanding virtual, override, and new keywords.

Simple class inheritance: Example

Let's see in theC# compiler, the example of when we need a new keyword.
 
using System;
namespace Polymorphism
{
 class A
 {
 public void Test() { Console.WriteLine("A::Test()"); }
 }
 class B : A { }
 class C : B { }
 class Program
 {
 static void Main(string[] args)
 {
 A a = new A();
 a.Test(); 
 B b = new B();
 b.Test(); 
 C c = new C();
 c.Test();
 Console.ReadKey();
 }
 }
}
   

Output:

A::Test()
A::Test()
A::Test()

Suppose a method Test() is declared in the base class A and classes B or C have no methods as shown above. Here conceptually, a derived class is a specialization of the base class. Because of this, it is possible to inherit fields and methods from one class to another class easily. In short, it is mainly useful for code reusability.

Read More - C# Interview Questions And Answers

Warning: Use the new keyword if hiding was intended:

 
using System;
namespace Polymorphism
{
 class A
 {
 public void Test() { Console.WriteLine("A::Test()"); }
 }

 class B : A
 {
 public void Test() { Console.WriteLine("B::Test()"); }
 }

 class C : B
 {
 public void Test() { Console.WriteLine("C::Test()"); }
 }

 class Program
 {
 static void Main(string[] args)
 {
 
 A a = new A();
 B b = new B();
 C c = new C();

 a.Test(); 
 b.Test();
 c.Test(); 

 a = new B();
 a.Test(); 

 b = new C();
 b.Test(); // 

 Console.ReadKey();
 }
 }
}

  

Output:

A::Test() B::Test() C::Test() A::Test() B::Test()

Now, Suppose you have the Test() method in all the classes A, B, and C as shown above program. The output will be as shown in the above window. Also when you run the above program, it will run successfully and give the O/P without getting any error. But It gives a warning as shown below:

  • Warning: 'Polymorphism.B.Test()' hides inherited member 'Polymorphism.A.Test()'. Use the new keyword if hiding was intended.

The solution to this problem is already shown in the warning. Just read it carefully. Yes, you got that, To remove that warning we need to use the NEW keyword.

New Keyword (Method Hiding)

As you have seen in the above example the compiler generates the warnings. The great solution is you have to hide the base class method from the derived class here just declare the derived class method with the "new" keyword. Hence, the above code can be re-written as :

 using System;
namespace Polymorphism
{
 class A
 {
 public void Test() { Console.WriteLine("A::Test()"); }
 }

 class B : A
 {
 public new void Test() { Console.WriteLine("B::Test()"); }
 }

 class C : B
 {
 public new void Test() { Console.WriteLine("C::Test()"); }
 }

 class Program
 {
 static void Main(string[] args)
 {
 
 A a = new A();
 B b = new B();
 C c = new C();

 a.Test(); 
 b.Test(); 
 c.Test(); 

 a = new B();
 a.Test();

 b = new C();
 b.Test(); 

 Console.ReadKey();
 }
 }
}
 

Output:

A::Test()
B::Test()
C::Test()
A::Test()
B::Test()
Moreover, In the above example, the new keyword hides a method in a base class (Class A). Hence when you are creating a method with the same name in a derived class as the method in the base class. We use the new keyword. This is known as method hiding.

Virtual and Override keywords (Method Overriding)

Virtual keyword:

It is used to specify the virtual method in the base class and the method with the same signature that needs to be overridden in the derived class.

Override keyword:

We generally use override with virtual. When we need to override the base class method into a derived class then we use the override keyword.

Virtual and Override keyword Example:

 using System;
namespace Polymorphism
{
 class A
 {
 public virtual void Test() { Console.WriteLine("A::Test()"); }
 }

 class B : A
 {
 public override void Test() { Console.WriteLine("B::Test()"); }
 }
 
 class C : B
 {
 public override void Test() { Console.WriteLine("C::Test()"); }
 }
 
 class Program
 {
 static void Main(string[] args)
 {
 
 A a = new A();
 B b = new B();
 C c = new C();
 a.Test();
 b.Test(); 
 c.Test(); 
 
 a = new B();
 a.Test();
 
 b = new C();
 b.Test(); 

 Console.ReadKey();
 }
 }
}

Output:


A::Test()
B::Test()
C::Test()
B::Test()
C::Test()

In C#, for overriding the base class method in a derived class, you have to declare a base class method as virtual and a derived class method overrides are shown in the above programming window. In short, the virtual keyword in the base class allows for method overriding in derived classes, and the override keyword in the derived classes indicates the specific implementation of the method. Allowing different versions of the Test method to be called based on the actual type of the object at runtime, enables polymorphic behavior.

Mixing Method Overriding and Method Hiding

You can also mix the method hiding and method overriding by using virtual and new keywords. I am overriding the Class B, Test() method in Class C as shown below:

 
using System;
namespace Polymorphism
{
 class A
 {
 public void Test() { Console.WriteLine("A::Test()"); }
 }

 class B : A
 {
 public new virtual void Test() { Console.WriteLine("B::Test()"); }
 }

 class C : B
 {
 public override void Test() { Console.WriteLine("C::Test()"); }
 }

 class Program
 {
 static void Main(string[] args)
 {

 A a = new A();
 B b = new B();
 C c = new C();

 a.Test(); 
 b.Test(); 
 c.Test(); 

 a = new B();
 a.Test(); 

 b = new C();
 b.Test();

 Console.ReadKey();
 }
 }
}
  

Output:

A::Test()
B::Test()
C::Test()
A::Test()
C::Test()

In short, here the new keyword in class B is used for method hiding, which also indicates that the Test() method in B is not intended to override the method in A. The virtual keyword in class B allows us to further override derived classes. The override keyword in class C is used to explicitly override the method in B. It shows polymorphic behavior where the method called is determined at runtime based on the actual type of the object.

Note

  1. The virtual keyword is used to modify a method, property, indexer, or event declared in the base class and allow it to be overridden in the derived class.

  2. The override keyword is used to extend or modify a virtual/abstract method, property, indexer, or base class event into a derived class.

  3. The new keyword hides a method, property, indexer, or base class event into a derived class.

The difference between virtual override and new keyword in c#

virtualoverridenew
Used for method, property, or indexer in a parent class.Used for method, property, or indexer in a Child class.Applied to a method, property, or indexer in a Child class.
It indicates that the method, property, or indexer can be overridden in Child classes.It informs the compiler that the method, property, or indexer is intended to override a virtual or abstract member in the parent class.It hides a member that is declared in a parent class. It does not override the member but instead creates a new member with the same name.
Used in the base class to provide a default implementation that can be overridden by derived classes.Must be used only if there is a corresponding virtual or abstract member in the parent class.Use new when you intentionally want to hide a parent class member, and there is no intention to participate in polymorphism.

Unlock the next level of C#

Summary

I have briefly explained these keywords, which are very important for beginners in both C# and OOPS. If you have a good understanding of OOPS concepts, you can win in any object-oriented language. So study OOPS concepts first then go for C#. Also, I would like to have feedback from my blog readers. Your valuable feedback, questions, or comments about this article are always welcome. And don't forget to enroll in the C-sharp programming course. Enjoy coding...!

FAQs

Q1. What is the use of new and override in C#?

The override keyword is used to modify a virtual/abstract method, property, indexer, or event of a base class into a derived class. The new keyword is used to hide a method, property, or event of the base class into a derived class.

Q2. What is the difference between new and override in C#?

The override keyword overrides the functionality of a virtual method in a base class, providing different functionality. The new keyword hides the original method providing different functionality.

Q3. Is it mandatory to use virtual and override keywords in C#?

When the method is declared as virtual in a base class, and the same definition exists in a derived class, there is no need for override, but it will only work if the method is overridden in the derived class.

Take our free csharp skill challenge to evaluate your skill

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET CHALLENGE

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this