Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you want to hide a method using `new`? [duplicate]

Possible Duplicate:
C# - new keyword in method signature

Let's say I have 3 classes: GrandDad, Dad, Son. Son inherits from Dad, which inherits from GrandDad.

Each class implements foo.

// GrandDad class: 
public virtual void foo()

// Dad class: 
new public virtual void foo()

// Son class: 
public override void foo()

I don't understand the reason as to why Dad would use the new keyword. As I understand, using new hides a method. Why would you want to do this?

I read the MSDN explanation of new, but the discussion was only mechanical, rather than architectural.

Thanks

like image 854
Kevin Meredith Avatar asked Aug 25 '11 01:08

Kevin Meredith


1 Answers

Your presented code isn't a very good example, but one general use case for 'new' is if a base class is modified to add a new method (typically a base class beyond your control), but you have existing code that needs to call your derived class method with the same name. Changing the derived class method to 'new' allows you to remain compatible with existing consumers of your public interface.

like image 170
Dan Bryant Avatar answered Oct 02 '22 21:10

Dan Bryant