The base keyword is used to access members of the base class from within a derived class:
A base class access is permitted only in a constructor, an instance method, or an instance property accessor.
It is an error to use the base keyword from within a static method.
In this example, both the base class, Person
, and the derived class, Employee
, have a method named Getinfo
. By using the base keyword, it is possible to call the Getinfo
method on the base class, from within the derived class.
// Accessing base class members using System; public class Person { protected string ssn = "444-55-6666"; protected string name = "John L. Malgraine"; 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("Emplyee ID: {0}", id); } } class TestClass { public static void Main() { Employee E = new Employee(); E.Getinfo(); } }
Name: John L. Malgraine SSN: 444-55-6666 Emplyee ID: ABC567EFG
For additional examples, see new, virtual, and override.
This sample shows how you can specify the base-class constructor called when creating instances of a derived class.
using System; public class MyBase { int num; public MyBase() { Console.WriteLine("in MyBase()"); } public MyBase(int i ) { num = i; Console.WriteLine("in MyBase(int i)"); } public int GetNum() { return num; } } public class MyDerived : MyBase { static int i = 32; // this constructor will call Base::Base() public MyDerived(int ii) : base() { } // this constructor will call Base::Base(int i) public MyDerived() : base(i) { } public static void Main() { MyDerived md = new MyDerived(); MyDerived md1 = new MyDerived(1); } }
in MyBase(int i) in MyBase()