Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access functionality of inherited classes easily?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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) 
   ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading