Using the `base` Keyword in C# for Inheritance: Accessing Base Class Members
Learn how to use the `base` keyword in C# to access members (fields, methods, constructors) of a base class from within a derived class. This tutorial explains how `base` facilitates working with inheritance, particularly when dealing with naming conflicts between base and derived classes.
Using the `base` Keyword in C# for Inheritance
Introduction
In C#, the `base` keyword provides a way to access members (fields, methods, constructors) of a base class from within a derived class. This is particularly useful when dealing with inheritance and when both base and derived classes have members with the same name.
Accessing Base Class Fields
If a derived class has a field with the same name as a field in its base class, you can use `base` to explicitly access the base class's field.
Accessing Base Class Fields
using System;
public class Animal {
public string color = "white";
}
public class Dog : Animal {
string color = "black";
public void ShowColor() {
Console.WriteLine($"Animal color: {base.color}");
Console.WriteLine($"Dog color: {color}");
}
}
class TestBase {
static void Main(string[] args) {
Dog d = new Dog();
d.ShowColor(); // Output: Animal color: white, Dog color: black
}
}
Calling Base Class Methods
Similarly, you can call a base class method from a derived class using `base`. This is especially important if the derived class overrides the base class method.
Calling Base Class Methods
using System;
public class Animal {
public virtual void Eat() {
Console.WriteLine("Eating...");
}
}
public class Dog : Animal {
public override void Eat() {
base.Eat(); // Calls the base class's Eat() method
Console.WriteLine("Eating bread...");
}
}
class TestBase {
static void Main(string[] args) {
Dog d = new Dog();
d.Eat(); // Output: Eating..., Eating bread...
}
}
Calling Base Class Constructors
When a derived class's constructor is called, the base class's constructor is implicitly invoked *before* the derived class's constructor's code executes. You can explicitly call the base class constructor using `base()`.
Calling Base Class Constructor
using System;
public class Animal {
public Animal() {
Console.WriteLine("Animal constructor...");
}
}
public class Dog : Animal {
public Dog() {
Console.WriteLine("Dog constructor...");
}
}
class TestOverriding {
static void Main(string[] args) {
Dog d = new Dog(); // Output: Animal constructor..., Dog constructor...
}
}
Important Note: `base` Keyword Restrictions
The `base` keyword can only be used within instance methods, constructors, or instance property accessors. It cannot be used inside static methods.
Conclusion
The `base` keyword is crucial for working with inheritance in C#. It allows for clear access to base class members, enabling code reuse and extending functionality while maintaining a structured inheritance hierarchy.