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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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));
    }
}

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


769-001