What is the significance of the "base" keyword in C# and how is it used in inheritance?
What is the significance of the "base" keyword in C# and how is it used in inheritance?
757
02-Jul-2023
Updated on 04-Jul-2023
Aryan Kumar
04-Jul-2023In C#, the
basekeyword is used to access members of the base class from within a derived class. It can be used to:For example, consider the following code:
C#
In this code, the
BaseMethod()method is overridden in theDerivedClassclass. When theBaseMethod()method is called on thederivedClassobject, the overridden version of the method is executed. However, if we want to call the original version of theBaseMethod()method, we can use thebasekeyword. For example:C#
The
basekeyword can also be used to specify which base-class constructor should be called when creating instances of the derived class. For example:C#
In this code, the
DerivedClassclass has two constructors. The default constructor calls theBaseClassconstructor, and the parameterized constructor does not call theBaseClassconstructor. When we create aDerivedClassobject without passing any parameters, the default constructor is called. However, if we pass a parameter to theDerivedClassconstructor, the parameterized constructor is called, and theBaseClassconstructor is not called.The
basekeyword is a powerful tool that can be used to access members of the base class from within a derived class. It can be used to call methods, specify constructors, and more.