#769 – Pattern – Call a Base Class Method When You Override It

You can call a method in a class’ base class using the base keyword. You can do this from anywhere within the child class, but  it’s a common pattern to call the base class method when you override it.  This allows you to extend the behavior of that method.

Here’s an example.

    public class Dog
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }

        public virtual void DumpInfo()
        {
            Console.WriteLine(string.Format("Dog {0} is {1} years old", Name, Age));
        }
    }

    public class Terrier : Dog
    {
        public double GrowlFactor { get; set; }

        public Terrier(string name, int age, double growlFactor)
            : base(name, age)
        {
            GrowlFactor = growlFactor;
        }

        public override void DumpInfo()
        {
            base.DumpInfo();

            Console.WriteLine(string.Format("  GrowlFactor is {0}", GrowlFactor));
        }
    }

 

            Terrier t = new Terrier("Jack", 17, 9.9);
            t.DumpInfo();

769-001

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.

2 Responses to #769 – Pattern – Call a Base Class Method When You Override It

  1. Pingback: Dew Drop – January 30, 2013 (#1,490) | Alvin Ashcraft's Morning Dew

  2. Pingback: Interesting .NET Links – January 31 , 2013 | TechBlog

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: