Chris
Chris

Reputation: 159

Determine object type at run time - C#

I have the 2 sub classes called CalIntEvent and CalExtEvent which have two properties called custId and roomNumber. The classes inherit from CalEvent.

I have the below code but cannot access the derived class properties. How do I access these?

CalEvent newEvent;   
while (userAns != '1' && userAns != '2')
{
    Console.WriteLine("\nPlease enter 1 for Internal Event or 2 for External Event: ");
    userAns = Console.ReadKey().KeyChar;

}

if (userAns == '1')
{
    newEvent = new CalIntEvent();

}
else
{
    newEvent = new CalExtEvent();
    newEvent.custId = 2;// issue is here<<<<<<
}
newEvent.location = GetUserInput(Field.Location, "Please enter a location");
newEvent.title = GetUserInput(Field.Title, "Please enter a title");
newEvent.description = GetUserInput(Field.Description, "Please enter a description");   

Upvotes: 0

Views: 45

Answers (1)

Yacoub Massad
Yacoub Massad

Reputation: 27861

Since custId is defined on CalExtEvent, then you cannot access it from a variable of type CalEvent.

What you can do is to initialize that property upon the construction of CalExtEvent. Here is an example:

newEvent = new CalExtEvent() { custId = 2};

Upvotes: 2

Related Questions