The base Keyword
Accessing members of the base class from within a derived class.
Calling a base-class constructor when creating instance of the derived class.
With base keyword we access base class property non-virtually.
With base we call a method on the base class that has been overridden by another method.
base class is permitted only in a constructor, instance method, instance property accessor.
You cannot use base keyword from within static method.
public class Person
{
protected string ssn = "555-55-5555";
protected string name = "John L. Doe";
public virtual void GetInfo()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("SSN: {0}", ssn);
}
}
class Employee : Person
{
public string id = "ABC567EFG";
public override void GetInfo()
{
// Calling the base class GetInfo method:
base.GetInfo();
Console.WriteLine("Employee ID: {0}", id);
}
}
class TestClass
{
static void Main()
{
Employee E = new Employee();
E.GetInfo();
}
}
/*
Output
Name: John L. Doe
SSN: 555-55-5555
Employee ID: ABC567EFG
*/
static void Main()
{
House mansion = new House { Name="McMansion", Mortgage=250000 };
Console.WriteLine (mansion.Liability); // 250000
}
public class Asset
{
public string Name;
public virtual decimal Liability => 0; // Virtual
}
public class House : Asset
{
public decimal Mortgage;
public override decimal Liability => base.Liability + Mortgage; //using base keyword
}
public class Stock : Asset
{
public long SharesOwned;
// We won't override Liability here, because the default implementation will do.
}