CodeBlanks Logo Icon CodeBlanks

The base keyword

C# course · Intermediate · Lesson 14/116

Learn to call the base class constructor and methods with base.

The base keyword

The base keyword lets a derived class reach members of its base class. Its most common use is calling the base constructor: public SavingsAccount(string owner) : base(owner) { ... }.

Here : base(owner) calls the owner-parameter constructor of Account first. The derived class body cannot run before the base constructor finishes. base is also used to reach base class methods and fields.

Base constructor with base()

If the base class has a parameterized constructor, the derived class must call it explicitly. The : base(...) expression is written before the body. Otherwise the compiler looks for a parameterless base constructor and errors if none exists.

The execution order is: the base constructor finishes completely first, then the derived class body runs. This ensures the base class is prepared first; the derived class can safely access its members.

Exercise Define SavingsAccount with base

The Account base class below is given (constructor public Account(string owner) assigns to Owner). Declare a derived SavingsAccount class whose constructor is public SavingsAccount(string owner) : base(owner) and add a public decimal Balance { get; set; } property. Inside Main create an instance with new SavingsAccount("Alex") and print Owner.

Show example solution
Account. The constructor starts with : base(owner). In Main write SavingsAccount s = new SavingsAccount("Alex"); Console.WriteLine(s.Owner);
Example solution:
using System;

class Account
{
    public string Owner { get; set; }

    public Account(string owner)
    {
        Owner = owner;
    }
}

class SavingsAccount : Account
{
    public decimal Balance { get; set; }

    public SavingsAccount(string owner) : base(owner)
    {
    }
}

class Program
{
    static void Main()
    {
        SavingsAccount s = new SavingsAccount("Alex");
        Console.WriteLine(s.Owner);
    }
}

Test yourself

  1. Complete the base call

    public SavingsAccount(string owner) : ____(owner) { }
    Show answer
    public SavingsAccount(string owner) : base(owner) { }
  2. What is the execution order?

    public SavingsAccount(string o) : base(o) { ... }
    • Derived body first, then base
    • Base constructor first, then derived body
    • Only derived
    • Only base
    Show answer

    Base constructor first, then derived body — Correct. The base class runs first, the derived class after.

  3. Match each base usage to its purpose

    : base(owner)
    Calls base constructor
    base.Method()
    Calls base method
    base
    The base class
    owner
    The argument passed

All lessons in Intermediate