#618 – Use the base Keyword to Call A Method in the Base Class

If a derived class does not provide its own version of a method that it inherits from the base class, it can call the method in the base class directly, by name.

However, if the derived class replaces (using the new keyword) or overrides the base class method, it can still call the version of the method that exists in the base class, using the base keyword.

    public class Dog
    {
        public virtual void Bark()
        {
            Console.WriteLine("Dog barking: Woof");
        }
    }

    public class Terrier : Dog
    {
        public override void Bark()
        {
            Console.WriteLine("Terrier barking: Growf");
            base.Bark();   // Call Dog.Bark
        }
    }

Now when we call Bark on an instance of a Terrier, its version of Bark will call the version defined in Dog.

        static void Main()
        {
            Terrier jack = new Terrier();
            jack.Bark();
        }

Advertisement

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

One Response to #618 – Use the base Keyword to Call A Method in the Base Class

  1. Pingback: #769 – Pattern – Call a Base Class Method When You Override It « 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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: