#343 – Use the new Keyword to Replace a Method in a Base Class
June 10, 2011 3 Comments
A derived class inherits data and behavior from its parent class.
There are times when you might want to replace a method in a base class with a new method in the derived class, having the same name. You can do this using the new keyword.
Assume a Dog class has a Bark method:
public class Dog { public void Bark() { Console.WriteLine("Generic dog {0} says Woof", Name); }
You can provide a new version of this method in a class that derives from Dog, using the new keyword. This new method hides the method in the base class.
public class Terrier : Dog { public new void Bark() { Console.WriteLine("Terrier {0} is barking", Name); }
Dog objects will now invoke Dog.Bark and Terrier objects will invoke Terrier.Bark.
Dog kirby = new Dog("Kirby", 15); kirby.Bark(); Terrier jack = new Terrier("Jack", 17); jack.Bark();
Pingback: #618 – Use the base Keyword to Call A Method in the Base Class « 2,000 Things You Should Know About C#
Pingback: #677 – Method Marked with new Modifier Cannot Be Overridden « 2,000 Things You Should Know About C#
Pingback: #723 – New Methods in Subclass May Not Be Visible in Derived Classes « 2,000 Things You Should Know About C#