BaseKeyword is used to access a member of the base class from a derived class:
Base Class access can only be performed in constructors, instance methods, or instance attribute accessors.
Use from static methodsBaseKeyword is incorrect.
Example
In this example, the base classPersonAnd Derived classesEmployeeEach has a nameGetinfo. UseBaseKeyword. You can callGetinfoMethod.
// keywords_base.cs// Accessing base class membersusing 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("Employee ID: {0}", id); }}class TestClass{ static void Main() { Employee E = new Employee(); E.GetInfo(); }}
This example shows how to specify the base class constructor called when creating a derived class instance.
// keywords_base2.csusing System;public class BaseClass{ int num; public BaseClass() { Console.WriteLine("in BaseClass()"); } public BaseClass(int i) { num = i; Console.WriteLine("in BaseClass(int i)"); } public int GetNum() { return num; }}public class DerivedClass : BaseClass{ // This constructor will call BaseClass.BaseClass() public DerivedClass() : base() { } // This constructor will call BaseClass.BaseClass(int i) public DerivedClass(int i) : base(i) { } static void Main() { DerivedClass md = new DerivedClass(); DerivedClass md1 = new DerivedClass(1); }}
Output
Name: John L. MalgraineSSN: 444-55-6666Employee ID: ABC567EFG
For other examples, see new, virtual, and override.