Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / C#
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
3.43/5 (6 votes)
18 Apr 2011CPOL1 min read 15.4K   3   2
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Australia Australia
I am a Senior Software Developer / Technical Consultant in a leading software company.

Comments and Discussions

 
GeneralGood explanation & practice use. Pin
Tiep Le25-Apr-11 18:59
Tiep Le25-Apr-11 18:59 
Generalmy vote of 1 Pin
EngleA26-Apr-11 3:42
EngleA26-Apr-11 3:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.