Pages

Sunday, 28 June 2015

Base Access

Base Access

In some condition, we need to access base class inside of inherited class. If your derived class absolutely must access a hidden inherited member, you can access it by using a base access expression. This expression consists of the keyword base, followed immediately by a period and the name of the member, as shown in following syntax:
base.[Member Name]

Lets add some method in employee, just to show you how to access base class.
class person
{
 public string firstName;
 public string lastName;
 public ushort age;

 public void greet()
 {
  Console.WriteLine("Hello "+ firstName + " " + lastName);
 }
 
 public void talk(string words)
 {
  Console.WriteLine(firstName+" "+ lastName + " say "+ words);
 }
}

class employee : person
{
 public string company;
 new public void greet()
 {
  Console.WriteLine("Hello " + firstName + " " + lastName);
  Console.WriteLine("I work for " + company);
 }

 public void baseGreet()
 {
  Console.WriteLine("Accessing base class");
  base.greet();    //Accessing base class member
 }
}

class Program
{
 static void Main(string[] args)
 {
  employee me=null;

  me = new employee();
  me.firstName =  "Yang";
  me.lastName = "Sopiana";
  me.company = "Company.inc";
  me.age = 29;
  me.greet();
  me.baseGreet();
 }
}

The code will result following display:
Hello Yang Sopiana
I work for Company.inc
Accessing base class
Hello Yang Sopiana

0 comments:

Post a Comment