The 'base' Keyword
Part of the Object Oriented Programming section of Coddy's C# journey — lesson 20 of 70.
When a derived class inherits from a base class, you often need to access the parent's members directly. The base keyword provides this connection, allowing you to call the base class constructor or access its methods and properties.
The most common use of base is calling the parent's constructor. When creating a derived object, you can pass values up to the base class:
public class Animal
{
public string Name { get; set; }
public Animal(string name)
{
Name = name;
}
}
public class Dog : Animal
{
public string Breed { get; set; }
public Dog(string name, string breed) : base(name)
{
Breed = breed;
}
}The : base(name) syntax calls the Animal constructor before the Dog constructor body runs. This ensures the base class is properly initialized first.
You can also use base to call parent methods from within the derived class:
public class Animal
{
public void Speak()
{
Console.WriteLine("Animal sound");
}
}
public class Dog : Animal
{
public void Speak()
{
base.Speak(); // Calls Animal's Speak
Console.WriteLine("Woof!");
}
}Here, base.Speak() explicitly calls the parent's version of the method. This is useful when you want to extend the parent's behavior rather than completely replace it.
Challenge
EasyLet's build a product inventory system that demonstrates how derived classes use the base keyword to properly initialize their parent class and extend inherited behavior.
You'll create three files to organize your code:
Product.cs: Define aProductclass in theInventorynamespace. This base class represents any product with aNameproperty (string) andPriceproperty (decimal). Include a constructor that accepts both values and a methodGetInfo()that returns"{Name}: ${Price}".ElectronicProduct.cs: Define anElectronicProductclass in theInventorynamespace that inherits fromProduct. This class adds aWarrantyMonthsproperty (int). The constructor should accept name, price, and warranty months - usebaseto pass the name and price to the parent constructor. Create aGetInfo()method that first calls the parent'sGetInfo()usingbase, then appends" (Warranty: {WarrantyMonths} months)"to extend the output.Program.cs: In your main file, create anElectronicProductusing input values and display its complete information by callingGetInfo().
You will receive three inputs:
- Product name
- Price
- Warranty months
Print the result of calling GetInfo() on your electronic product.
For example, if the inputs are Laptop, 999.99, and 24, the output should be:
Laptop: $999.99 (Warranty: 24 months)Notice how the derived class builds upon the base class's output rather than duplicating the logic. The base keyword lets you reuse and extend the parent's behavior seamlessly!
Cheat sheet
The base keyword allows a derived class to access members of its parent class.
Use base to call the parent class constructor:
public class Animal
{
public string Name { get; set; }
public Animal(string name)
{
Name = name;
}
}
public class Dog : Animal
{
public string Breed { get; set; }
public Dog(string name, string breed) : base(name)
{
Breed = breed;
}
}The : base(name) syntax calls the parent constructor before the derived class constructor body executes, ensuring proper initialization.
Use base to call parent methods from the derived class:
public class Animal
{
public void Speak()
{
Console.WriteLine("Animal sound");
}
}
public class Dog : Animal
{
public void Speak()
{
base.Speak(); // Calls Animal's Speak
Console.WriteLine("Woof!");
}
}This allows you to extend parent behavior rather than completely replacing it.
Try it yourself
using System;
using Inventory;
class Program
{
public static void Main(string[] args)
{
// Read inputs
string name = Console.ReadLine();
decimal price = Convert.ToDecimal(Console.ReadLine());
int warrantyMonths = Convert.ToInt32(Console.ReadLine());
// TODO: Create an ElectronicProduct with the input values
// TODO: Print the result of calling GetInfo() on your electronic product
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesNamespaces & DirectivesIntro to Classes & ObjectsThe 'this' KeywordMethods and ParametersFields vs PropertiesConstructorsObject InitializersRecap - Simple Calculator4Inheritance
Basic Inheritance (:) SyntaxThe 'base' KeywordVirtual & Override KeywordsSealed ClassesThe 'object' Base ClassRecap - Employee Hierarchy7Advanced Features
Operator OverloadingIndexers (this[])ToString() OverrideExtension MethodsRecap - Custom List2Properties & Static Members
Auto-Implemented PropertiesRead/Write-Only PropertiesStatic Fields & MethodsStatic ClassesExpression-Bodied Members5Polymorphism & Interfaces
Compile vs Runtime PolyInterface vs Abstract ClassMultiple InterfacesExplicit InterfacesUpcasting & DowncastingRecap - Shape Calculator