I have the following class hierarchy of type Item:
Item
Weapon : Item
Armor : Item
I use a generic linked list of type Item. I have inserted different kinds of items: Armor, Weapon, etc. I stuck to two item types in this example.
I have the following code:
// Create the map. The underneath data structure is:
// Array2D<LinkedList<Item>> m_map;
// A generic 2d array contains a linked list of type cell at each cell.
// This makes it easy to drop and pick up items at a given player position.
Map map = new Map(10, 10);
// First, I store two items at position (0,0) on my map.
map.AddItem(0, 0, new Weapon(6));
map.AddItem(0, 0, new Armor(3));
// Now, this only retrieves weapons.
var qItems = from w in map.GetItems(0, 0)
where w is Weapon
select w;
// Weapons are outputted
foreach (Weapon weapon in qItems)
Console.WriteLine(weapon.m_damage);
This works fine, but when I'm interested in gathering all items (which will be often), I have to do this:
// All items are outputted
foreach (Item item in map.GetItems(0, 0))
{
if (item is Weapon)
Console.WriteLine("Damage: {0}", (item as Weapon).m_damage);
else if (item is Armor)
Console.WriteLine("AC: {0}", (item as Armor).m_ac);
}
Is there a more efficient way of retrieving different item types than using is/as? I think this can lead to bugs because what if a developer adds a new item type but forgets to make a condition for it in the foreach block? As you can guess, the list can get extensive of different types (10 or so in this project).
Edit: This is not a duplicate question. I'm looking at all subclasses, while the possible duplicate message is focused on retrieving one subclass.