#681 – Avoid Using the new Keyword To Hide Methods
September 28, 2012 2 Comments
You can use the new keyword in a derived class to hide a method in a base class, rather than overriding it. In other words, the method in the derived class is not polymorphic, so if the method is called from a variable whose type matches the base class, the method in the base class will be called, rather than the method in the subclass.
// In Dog - public virtual void Bark() // In Terrier : Dog - public new void Bark() Dog d = new Terrier("Bob"); d.Bark(); // Dog.Bark called, rather than Terrier.Bark
If a Terrier really is-a type of Dog, then this lack of polymorphism on the Bark method doesn’t really make sense. If you wanted to add a method to Terrier that was really something entirely new, you should give it a new name to avoid confusion, rather than using the new keyword.