21
NovUnderstanding virtual, override and new keyword in C#
C# Keywords: An Overview
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: 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.
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:
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
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.
The override keyword is used to extend or modify a virtual/abstract method, property, indexer, or base class event into a derived class.
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#
virtual | override | new |
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#
- 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
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
Take our Csharp skill challenge to evaluate yourself!
In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.