When we're dealing with inheritance in C#, it's common to want to automatically call the base method from an overridden method in a derived class.
One way to achieve this is by using the base
keyword. By including base.MethodName()
within our overridden method, we explicitly invoke the corresponding method in the base class.
This approach ensures that we maintain the functionality provided by the base class method while extending or modifying it in the derived class. It's particularly useful when we want to add extra functionality in addition to what the base method already does.
Let's understand with an example:
class MyBaseClass
{
public virtual void Display()
{
Console.WriteLine("Base class method");
}
}
class MyDerivedClass : MyBaseClass
{
public override void Display()
{
// Call the base method
base.Display();
// Add additional functionality
Console.WriteLine("Derived class method");
}
}
class Program
{
static void Main(string[] args)
{
MyDerivedClass obj = new MyDerivedClass();
obj.Display();
}
}
In above example, we have a base class named MyBaseClass with a virtual method called Display(). This method simply prints "Base class method" message to the console.
We also have a derived class named MyDerivedClass, which inherits from MyBaseClass. This derived class overrides the Display() method. Within the overridden method, it first calls the base method using base.Display() to ensures that the base class method is executed before any additional functionality is added.
After calling the base method, the derived class adds its own functionality by printing "Derived class method" to the console.
In Main method of Program.cs, we create an instance of MyDerivedClass and call its Display() method. As a result, the output we see on the console is:
This demonstrates how the base keyword allows us to automatically call the base method from within an overridden method in a derived class, allowing us to extend the functionality while maintaining the behavior provided by the base class method.
By automatically calling the base method, we adhere to the principles of code reuse and maintainability, as it allows us to control existing functionality without duplicating code.
Read Similar Articles
- [Answer]-"your cache folder contains root-owned files, due to a bug in npm err! previous versions of npm which has since been addressed."
- C#: Generating Random 6-Digit Number
- Hand Blenders Power Consumption Calculator | What is Power Consumption Of a Hand Blenders
- Create Stored Procedure with Return Values
- [Solved]-attributeerror: 'numpy.ndarray' object has no attribute 'dropna'
- [Fixed] Generate SQL Server database tables from C# classes | How To Convert C# Class to SQL table