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?
This uses the pattern-matching expression
portals[i] is Door door("expressionistype variable") to assign a Door-typed reference to the portal in question to the new variabledoor.You can even use the new variable directly after declaring it in the same
ifcondition: