#769 – Pattern – Call a Base Class Method When You Override It
January 30, 2013 2 Comments
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();