#343 – Use the new Keyword to Replace a Method in a Base Class

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();

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #343 – Use the new Keyword to Replace a Method in a Base Class

  1. Pingback: #618 – Use the base Keyword to Call A Method in the Base Class « 2,000 Things You Should Know About C#

  2. Pingback: #677 – Method Marked with new Modifier Cannot Be Overridden « 2,000 Things You Should Know About C#

  3. Pingback: #723 – New Methods in Subclass May Not Be Visible in Derived Classes « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: