Start learning free

LESSON 37 OF 69 · OBJECT-ORIENTED PROGRAMMING

Base Keyword in C#: Calling the Parent Method

Practice Read the full explanation

TL ; DR:

Inside an overriding method, base.Bark() calls the parent's version of Bark on the same object. This lets you extend the parent's behavior instead of replacing it.


class Puppy : Dog {
    public Puppy(string name) : base(name) { }
    public override void Bark() {
        base.Bark();   // do everything the parent did
        Console.WriteLine("Yip! Said " + name);
    }
}

Why it matters

Overriding a method replaces the parent's behavior. Often you want to extend it instead: keep what the parent did and add something more. A typical example is a save method: the parent writes the row to the database, and a subclass runs the parent's save first and then writes a log line.

Your task

The Puppy class already overrides Bark(), but the body is empty. Inside Puppy.Bark():

  1. call the parent's version with base.Bark();, so Woof! I am <name> still prints;
  2. then Console.WriteLine("Yip! Said " + name);.

Notes:

  • The constructor's : base(name) (already written) passes the name to Dog's constructor; base.Bark() does the same for a method.
  • Dog.Bark is virtual and Puppy.Bark is override; both are already written. name is a public field of Dog.

The driver (already written, it runs when you press Run):

Puppy buddy = new Puppy("Buddy");
buddy.Bark();
Puppy rex = new Puppy("Rex");
rex.Bark();
Dog dog = new Dog("Max");
dog.Bark();
  • buddy is a Puppy: its bark prints the parent's line, then its own.
  • rex is another Puppy: the names come from the object, nothing is hard-coded.
  • dog is a plain Dog: its bark is unchanged and prints only the parent's line, with no Yip!.

Expected output:

Woof! I am Buddy
Yip! Said Buddy
Woof! I am Rex
Yip! Said Rex
Woof! I am Max
STEP 1 OF 2
    Ctrl + Enter to check

    C# · OBJECT-ORIENTED PROGRAMMING

    Base Keyword in C#, explained

    What base does

    When a subclass overrides a method, the new body replaces the parent's body for objects of that subclass. Often you want to keep what the parent did and add something to it. Inside the subclass, the keyword base refers to the parent class, so base.Bark() runs the parent's version of Bark on the same object.

    You have already seen base in constructors: : base(name) passes the name to the parent's constructor. base.Bark() is the same idea for an ordinary method.

    Why extending beats copying

    You could make Puppy print the Woof! line itself by typing the same Console.WriteLine again. That works until someone changes Dog.Bark: the puppy's copy would still print the old text. Calling base.Bark() keeps a single copy of the parent's behaviour, so every subclass that extends it follows the parent automatically.

    The call also runs on the same object. That is why the parent's line shows the puppy's own name: base.Bark() does not create a Dog, it runs Dog's code with this still being the puppy.

    The classes in this lesson

    Dog has a public field name and a method Bark that prints Woof! I am followed by the name. Bark is marked virtual, which allows subclasses to override it. Puppy extends Dog and declares public override void Bark(), but the body is empty, so a puppy would print nothing at all.

    Step by step

    1. Call the parent first. Inside Puppy.Bark, write base.Bark();. This runs Dog's version, which prints the Woof! line using the puppy's own name.
    2. Add the puppy's own line. Print "Yip! Said " followed by name. The field is inherited from Dog, so Puppy can use it directly.

    The solution in C#

    class Dog {
        public string name;
        public Dog(string name) { this.name = name; }
        public virtual void Bark() {
            Console.WriteLine("Woof! I am " + name);
        }
    }
    
    class Puppy : Dog {
        public Puppy(string name) : base(name) { }
        public override void Bark() {
            base.Bark();
            Console.WriteLine("Yip! Said " + name);
        }
    }
    
    class Solution {
        public void MainFunction() {
            Puppy buddy = new Puppy("Buddy");
            buddy.Bark();
            Puppy rex = new Puppy("Rex");
            rex.Bark();
            Dog dog = new Dog("Max");
            dog.Bark();
        }
    }
    

    Running it prints:

    Woof! I am Buddy
    Yip! Said Buddy
    Woof! I am Rex
    Yip! Said Rex
    Woof! I am Max
    

    Each puppy prints two lines, parent line first. The plain Dog prints only the parent's line, because its own Bark was never changed.

    Details worth knowing

    • virtual and override go together. A method can only be overridden if the parent marks it virtual, and the subclass must say override. Both are already written for you here.
    • The order is your choice. Putting base.Bark() first gives the parent's line before the puppy's. If a puppy method printed its own line and then called base.Bark(), the output for a puppy named Zed would be Yip! Said Zed and then Woof! I am Zed.
    • Without the call, the parent's code does not run. If the override only printed the Yip! line, a puppy named Zed would print just Yip! Said Zed. Overriding replaces; base is how you extend.
    • The override is used through a parent variable too. With Dog d = new Puppy("Pip");, calling d.Bark() prints Woof! I am Pip and then Yip! Said Pip. The object decides which version runs, not the type of the variable.

    How virtual and override choose a method

    Marking Dog.Bark as virtual means the version that runs is picked when the program runs, from the real type of the object. An object created with new Puppy("Pip") is a Puppy even when it is stored in a Dog variable, so its Bark is the puppy's. An object created with new Dog("Max") is a plain Dog, so it gets the parent's version. In the driver there is no if anywhere: each object simply carries its own behaviour.

    Changing the order

    The two statements in Puppy.Bark are independent, so you can swap them. With the Yip! line first and base.Bark() after it, a puppy named Zed prints:

    Yip! Said Zed
    Woof! I am Zed
    

    The lesson's tests expect the parent's line first, so keep base.Bark() above the puppy's own line.

    What goes wrong when base or virtual is missing

    If Dog.Bark were not marked virtual, the override would not compile. The compiler reports:

    error CS0506: 'Puppy.Bark()': cannot override inherited member 'Dog.Bark()' because it is not marked virtual, abstract, or override
    

    A related trap is writing Bark() instead of base.Bark() inside the override. That calls the puppy's own method again, which calls itself again, and the program ends in a stack overflow. The word base is what sends the call up to the parent.

    Common mistakes

    • Forgetting the parentheses and semicolon: the call is base.Bark();.
    • Typing the greeting again instead of calling base.Bark(). It would print the same text today, but it would stop matching the parent as soon as the parent changed.
    • Putting base.Bark() after the Yip! line. It compiles and runs, but the two lines come out in the wrong order for the lesson's expected output.
    • Using base in a method the parent does not have. base.Bark() compiles only because Dog declares an accessible Bark.
    • Hard-coding a name such as "Buddy". Use the name field, so every puppy prints its own name.

    Two uses of base

    WhereFormWhat it does
    After a constructor's parameters: base(name)Runs the parent's constructor with the given arguments, before the subclass constructor's body.
    Inside an overriding methodbase.Bark()Runs the parent's version of that method on the current object.

    Testing

    • Create new Puppy("Pip") and call Bark(): two lines, Woof! I am Pip and then Yip! Said Pip.
    • Create new Dog("Max") and call Bark(): one line, Woof! I am Max.

    Key takeaways

    • base.Method() calls the parent's version of a method on the current object.
    • An override replaces the parent's behaviour unless it calls base.
    • Where you place the base call decides whether the parent's work happens before or after the subclass's own.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free