Hello,

I'm having a bit of trouble with inheritance I was hoping one of you could help with.

I have a base clase; BaseGameEntity.

There are two classes which inherit from this, Drop and DropGuide.

I have an entity manager that stores all of the instance of Drop/DropGuide in a List<BaseGameEntity>.

The problem is when I use access an element in this list I can only seem to get to the "BaseGameEntity" parts of the object, how from there do I access the Drop/DropGuide that inherit from it?

Recommended Answers

All 5 Replies

Use the "as" keyword to cast them (I ignored the list portion for simplicity):

BaseGameEntity bge = new Drop();
(bge as Drop).DropMethod();

or you can use the old fashioned

((Drop) bge).DropMethod();

Use the "as" keyword to cast them (I ignored the list portion for simplicity):

BaseGameEntity bge = new Drop();
(bge as Drop).DropMethod();

or you can use the old fashioned

((Drop) bge).DropMethod();

Thanks, that's perfect.

Is there also a way to go through the list and manipulate each Drop whilst ignoring the DropGuides?

At the moment I've added a variable "type" and then used a for loop to go through each item then an if to check the type of object it is, this works perfectly well just seems there may be a more elegant solution I'm just not aware of.

I had initially thought a statement along the lines of foreach(Drop drop in entityList) would work - but that seems to take the dropguides and treat them as drops causing an error.

Yep, you can shift to using "is"

foreach(BaseGameEntity bge in entityList)
    if(entity is Drop)
       //process it

Embaressingly simple!

Thanks again.

Embaressingly simple!

Thanks again.

Nah, they're just new for a lot of people. They play very well with interfaces if you go down that road at a later time.

Never a problem.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.