Reputation: 9
so i Have a list consisting of different classes, all inheriting from a common class. Now i want to call for a method specific to one of those subclasses but i can't seem to find the right code to do that, could anyone help? the part of the code where it goes wrong (can't access the enemies list):
if (_floor.GetRoomByIndex(CheckActiveRoomIndex()).GetType() == typeof(StandardRoom))
{
for (int i = 0; i < _floor.GetRoomByIndex(CheckActiveRoomIndex()).enemies.Count; i++)
{
_floor.GetRoomByIndex(CheckActiveRoomIndex()).enemies[i].UpdateBoundingBox();
}
}
and here is part of my StandardRoom Class
class StandardRoom : CommonBaseClass
{
public bool IsCleared { get; set; }
public List<Enemy> ennemies = new List<Enemy>();
...
}
Upvotes: 0
Views: 67
Reputation: 4913
William,
The problem is that _floor.GetRoomByIndex(CheckActiveRoomIndex())
is not a StandardRoom, but a Room (or the base class, whatever the name)
1/ Solution closer to existing code There is cast missing so that the rooms can be treated as StandardRoom : use the as keyword to cast in a safe way.
And Don't Repeat Yourself (DRY principle), declare a variable (stdRoom).
StandardRoom stdRoom = _floor.GetRoomByIndex(CheckActiveRoomIndex()) as StandardRoom;
if ( stdRoom != null )
{
for (int i = 0; i < stdRoom.enemies.Count; i++)
{
stdRoom.enemies[i].UpdateBoundingBox();
}
}
As says Olivier below, with C#7 pattern matching (Visual Studio 2017+), the cast can be shorter :
if ( _floor.GetRoomByIndex(CheckActiveRoomIndex()) is StandardRoom stdRoom )
2/ The Linq answer
Enumerable.SelectMany
can be used to get Enemies from a Room
if ( _floor.GetRoomByIndex(CheckActiveRoomIndex()) is StandardRoom stdRoom )
{
// projection to get Enemies from StandardRoom
foreach( Enemy e in stdRoom.SelectMany( r => r.enemies ) )
{
e.UpdateBoundingBox()
}
}
Regards
Upvotes: 2
Reputation: 4489
LINQ has a tons of available methods. Read the documentation or just google 'LINQ methods'.
The method you are looking for is OfType<T>
(see documentation page). This method will only select the items in the list of the required type T
.
Upvotes: 1