What is base keyword in C#: Explanation and Examples
base keyword is used to access members of a class's direct parent (base) class. It allows you to call base class constructors, methods, or properties from a derived class to reuse or extend functionality.How It Works
Imagine you have a family tree where a child inherits traits from their parent. In programming, a derived class inherits features from a base class. The base keyword acts like a bridge that lets the child class reach back to its parent to use or extend those inherited features.
When you use base, you can call the parent class's constructor to set up initial values or invoke a method that the child class wants to build upon or override. This helps avoid repeating code and keeps your program organized.
Example
This example shows a base class Animal with a method and a constructor. The derived class Dog uses base to call the parent constructor and method.
using System; class Animal { public string Name; public Animal(string name) { Name = name; } public virtual void Speak() { Console.WriteLine("Animal speaks"); } } class Dog : Animal { public Dog(string name) : base(name) { } public override void Speak() { base.Speak(); // Calls Animal's Speak method Console.WriteLine(Name + " barks"); } } class Program { static void Main() { Dog dog = new Dog("Buddy"); dog.Speak(); } }
When to Use
Use base when you want to reuse or extend functionality from a parent class inside a child class. For example, call the base class constructor to initialize inherited fields or call a base method before adding extra behavior.
This is common in object-oriented programming when building on existing code without rewriting it, such as customizing behavior in a specialized class while keeping the core logic from the base class.
Key Points
baseaccesses members of the immediate parent class.- It helps call base class constructors and methods.
- Useful for extending or customizing inherited behavior.
- Prevents code duplication by reusing base class logic.