faizanjehangir
faizanjehangir

Reputation: 2849

Cannot access public properties in derived class

I have an abstract class which is inherited by another class as following:

public abstract class Employee
{
        public string name{ get; set; }
        public string age { get; set; }
}

public class OtherEmployee : Employee
    {
        public OtherEmployee()
        {
        }

        public string specialField{ get; set; }
    }

This is what I am doing and somehow, not getting it done:

Employee otherEmployee= new OtherEmployee();
otherEmployee.specialField = "somevalue";

I am not provided with the access to specialField, whereas all the attributes of Employee are accessible. I know it is a trivial problem, but I have hit a roadblock here..

Upvotes: 1

Views: 2397

Answers (3)

Stefano Bafaro
Stefano Bafaro

Reputation: 913

You have to write in this way beacause you daeclare otheremployee variable as Employee Type, so it doesn't know about special field. So:

(otherEmployee as OtherEmployee).specialField = "somevalue";

Upvotes: 0

Carbine
Carbine

Reputation: 7903

You will not have access to specialField because the object is created with the base class reference. It will not have access to the Child class properties.

Though the object is instantiated with a child Class, the reference still points to base class. So the properties/skeleton will be of base class and it would not have memory allocated for child class structure.

Upvotes: 2

germi
germi

Reputation: 4668

Employee doesn't know about specialField, only OtherEmployee does. You need to cast it to the right class to use specialField.

Employee otherEmployee = new OtherEmployee();

This doesn't give you an OtherEmployee but an Employee. To be able to use specialField do something like this:

(otherEmployee as OtherEmployee).specialField = yourValue;

Upvotes: 5

Related Questions