How to access functionality of inherited classes easily?

63 Views Asked by At

Let's say Door inherits from Portal and has a field locked (bool). portals is an array of Portal

The following code is invalid as I try to access a field not belonging to the class I'm working with:

for (int i = 0; i < portals.Length; ++i) 
{
if (portals[i] is Door) if (portals[i].locked == false) //...
}

Any easy way to access the derived class?

2

There are 2 best solutions below

0
On BEST ANSWER
if (portals[i] is Door door)
    if (door.locked == false) 
...

This uses the pattern-matching expression portals[i] is Door door ("expression is type variable") to assign a Door-typed reference to the portal in question to the new variable door.

You can even use the new variable directly after declaring it in the same if condition:

if (portals[i] is Door door && !door.locked) 
   ...
1
On

you can write like this:

if(portals[i] is Door door) if(door.locked == false) 

this would help you.