Using the New Keyword to shadow a method in a parent class






3.43/5 (6 votes)
Use of New / Shadowing in C# - Shadowing vs Overriding
We all know that the
New
keyword is used to shadow a function in the parent class. What it means is that in the child class, the method is treated as if it does not exist in the parent class. The question then arises as to what is the difference between shadowing and overriding? You can as well define a virtual method and override it in the child class. Why do we need New
keyword?
The answer is that shadowing helps you "override" a function in a parent method even if that is not marked virtual. In other words, it helps you override a non virtual method in the child class.
A typical use - Consider a class library being used by various modules in a project. There is a method which is being referenced by numerous modules and libraries. You need to make a change in that method but you are not sure if that is going to break the functionality of the modules already referencing that. So you define a class inheriting from the parent class and shadow the method using new
keyword. You use your own shadowed method for your logic while not breaking any code due to your change.