#345 – Method in Derived Class Hides Base Class Method by Default

If you define a method in a derived class with the same name and signature as a method in the base class, the new method hides the base class method by default.  This is true even if you don’t use the new keyword to explicitly indicate that you intend to hide the method in the base class.

In other words, if we have a Dog.Bark method, the following two code snippets are functionally equivalent.

    public class Terrier : Dog
    {
        public new void Bark()
        {
            Console.WriteLine("Terrier {0} is barking", Name);
        }
    }

 

    public class Terrier : Dog
    {
        // No new keyword, but we're still hiding base class method
        public void Bark()
        {
            Console.WriteLine("Terrier {0} is barking", Name);
        }
    }

Without the new keyword, the compiler warns you that you’re hiding the base class method and recommends using the new keyword.

Advertisement

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

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: