Click here to Skip to main content
Click here to Skip to main content

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

By , 18 Apr 2011
Rate this:
Please Sign up or sign in to vote.
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)

About the Author

anshudutta
Software Developer (Senior)
Singapore Singapore
I am a Senior Software Developer / Technical Consultant in a leading software company. I have 9+ years of development experience in .NET, C# VB and SQL
Follow on   Twitter

Comments and Discussions

 
GeneralGood explanation & practice use. PinmemberTiep Le25-Apr-11 18:59 
Generalmy vote of 1 PinmemberEngleA26-Apr-11 3:42 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 18 Apr 2011
Article Copyright 2011 by anshudutta
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid