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?
CodePudding user response:
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)
...
CodePudding user response:
you can write like this:
if(portals[i] is Door door) if(door.locked == false)
this would help you.