Browse Tutorials
Understanding virtual, override and new keyword in C#

Understanding virtual, override and new keyword in C#

29 Feb 2024
Intermediate
95.8K Views
17 min read
Learn via Video Course & by Doing Hands-on Labs

C# Programming For Beginners Free Course

virtual, override, and new keywords in C#: An Overview

Inobject-oriented programming, understanding the concept of polymorphism is very necessary for a programmer. Hence in this C# Tutorial, We will explore different types of methods and their keywords. Meanwhile Enrolling in the top C-sharp Programming Coursewillsurely help you in your C# learning journey. You will receive thorough insights into other object-oriented programming concepts effectively.

What is polymorphism?

These keywords play a pivotal role in shaping the behavior of classes. In this blog post, we'll explore these keywords and their significance in C#.
What is polymorphism?

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

Simple class inheritance: Example

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.

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.

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...!

Unlock the next level of C#

Introduction to C#: A Beginner's Guide

Objects and Classes in C#: Examples and Differences

Data Types in C# with Examples: Value and Reference Data Type

Conditional Statements in C#: if, if..else, Nested if, if-else-if

Scope of Variables in C#: Class Level, Method Level, and Block Level Scope OOPS Concepts

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