Pages

Sunday, 28 June 2015

Base Access From Instance

Base Access From Instance

An instance of a derived class consists of an instance of the base class plus the additional members of the derived class. A reference to the derived class points to the whole class object, including the base class part.

If you have a reference to a derived class object, you can get a reference to just the base class part of the object by casting the reference to the type of the base class by using the cast operator. The cast operator is placed in front of the object reference and consists of a set of parentheses containing the name of the class being cast to. Casting will be covered in next section.

See following example:
static void Main(string[] args)
{
 employee me=null;
 student mySon = null;

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

 person baseMe = (person)me;     //casting me object to person class
 Console.WriteLine("Accessing base from instance");
 baseMe.greet();
}

Our modified code now will display:
Hello Yang Sopiana
I work for Company.inc
Accessing base class
Hello Yang Sopiana
Accessing base from instance
Hello Yang Sopiana

0 comments:

Post a Comment