What really is the purpose of "base" keyword in c#?
The base
keyword is used to refer to the base class when chaining constructors or when you want to access a member (method, property, anything) in the base class that has been overridden or hidden in the current class. For example,
class A {
protected virtual void Foo() {
Console.WriteLine("I'm A");
}
}
class B : A {
protected override void Foo() {
Console.WriteLine("I'm B");
}
public void Bar() {
Foo();
base.Foo();
}
}
With these definitions,
new B().Bar();
would output
I'm B
I'm A
You will use base
keyword when you override
a functionality but still want the overridden functionality to occur also.
example:
public class Car
{
public virtual bool DetectHit()
{
detect if car bumped
if bumped then activate airbag
}
}
public class SmartCar : Car
{
public override bool DetectHit()
{
bool isHit = base.DetectHit();
if (isHit) { send sms and gps location to family and rescuer }
// so the deriver of this smart car
// can still get the hit detection information
return isHit;
}
}
public sealed class SafeCar : SmartCar
{
public override bool DetectHit()
{
bool isHit = base.DetectHit();
if (isHit) { stop the engine }
return isHit;
}
}
If you have the same member in class and it's super class, the only one way to call member from super class - using base
keyword:
protected override void OnRender(EventArgs e)
{
// do something
base.OnRender(e);
// just OnRender(e); will bring a StakOverFlowException
// because it's equal to this.OnRender(e);
}