Alex Rivera | Logout

C# List<baseClass> - any way to store inherited classes within, too?

Asked 2012-07-15T22:44:56.510
8

I am trying to create a simple "inventory" of items, much like in any RPG. I have very basic classes made, which have properties.

Anyway, I have a base class of item and inheriting from that is weapon. item has properties (name, value, weight, "important item") that are also used within weapon, but weapon has extra properties (attack, defense, speed, handedness).

I've got the following code (sorry if the readability is horrible):

static void Main(string[] args)
{   
     List<item> inventory = new List<item>();
     inventory.Add(new weapon("Souleater", 4000, 25.50f, false, 75, 30, 1.25f, 2));
                           //item--------------------------->  weapon--------->

     Console.Write("Name: {0}\nValue: {1}\nWeight: {2}\nDiscardable: {3}\nAttack: {4}\nDefense: {5}\nSpeed: {6}\nHandedness: {7}",
            inventory[0].Name, inventory[0].BValue, inventory[0].Weight, inventory[0].Discard, 
            inventory[0].Atk, inventory[0].Def, inventory[0].Speed, inventory[0].Hands);

     Console.ReadLine();
}

Basically, what I'm trying to do is add a new weapon to the inventory, but the inventory is a List<item> type. I went out on a whim hoping that, due to it's inheritance, it'd be accepted. It was, but the properties specific to weapon aren't able to be accessed:

('shopSystem.item' does not contain a definition for 'Atk' and no extension method 'Atk' accepting a first argument of type 'shopSystem.item' could be found)

So, is there any way to achieve what I was intending here? Have an "inventory" which can store item objects, as well as weapon, armour, accessory etc. objects, which inherit from item? It is also worth mentioning that I can access all of the desired properties if I declare

Edit
Report

1 Answer

2

You are doing the right thing by using a List<item> to store items and subclasses of items!

When you extract the item from the list, you just have to do a bit of work to test if it's a weapon, or some other kind of item.

To see if the element at position i on the array is a weapon, use the as operator, which will return null if the item is not the specified type (perhaps it is armour or some other type of item). This is known as a dynamic cast. It works even if the item is null.

weapon w = inventory[i] as weapon;  // dynamic cast using 'as' operator
if (w != null)
{
     // work with the weapon
}

Another way to do this is to check the type using the is operator before doing a static cast.

if (inventory[i] is weapon)
{
     // static cast (won't fail 'cause we know type matches)
     weapon w = (weapon)inventory[i];           

     // work with the weapon
} 
answered 2012-07-16T00:14:57.203

Your Answer