What is 'base' keyword?
In C#, the 'base' keyword is used to access members of the base class (also known as the parent class or superclass) from within a derived class (also known as the child class or subclass). It allows you to call constructors, methods, and properties of the base class, which can be useful when you want to reuse or extend functionality provided by the base class.
Here are a few common uses of the 'base' keyword in C#:
1. Calling Base Class Constructors: When a derived class constructor is invoked, it can use the 'base' keyword to explicitly call a constructor in the base class. This is useful when you want to ensure that the initialization logic in the base class constructor is executed before the derived class constructor's logic.
class BaseClass
{
public BaseClass(int value)
{
// Initialization logic
}
}
class DerivedClass : BaseClass
{
public DerivedClass(int value) : base(value)
{
// Derived class constructor logic
}
}
2. Accessing Base Class Members: When a derived class overrides a method or hides a member of the base class, you can use the 'base' keyword to access the original implementation of the member from within the derived class.
class BaseClass
{
public virtual void SomeMethod()
{
// Original implementation
}
}
class DerivedClass : BaseClass
{
public override void SomeMethod()
{
base.SomeMethod(); // Calls the base class implementation before adding additional logic
// Additional logic
}
}
Here's another example calling the base constructor and method of the base class using 'base' keyword:
3. Invoking Base Class Properties: When a derived class property overrides or hides a property of the base class, you can use the 'base' keyword to access the property of the base class.
class BaseClass
{
public virtual int Value { get; set; }
}
class DerivedClass : BaseClass
{
private int derivedValue;
public override int Value
{
get
{
return base.Value + derivedValue; // Accesses the base class property and adds derivedValue
}
set
{
base.Value = value; // Sets the base class property
}
}
}
In summary, the 'base' keyword in C# provides a way to interact with and access members of the base class within a derived class, enabling you to build upon or modify the functionality provided by the base class.