#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

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

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 comment