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

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: