0

I have something like this:

public class Item
{
    public int itemID;
    public string itemName;
}

public class Tool : Item
{
    public int toolDurability;
}

I want to create a Dictionary, something like

public Dictionary<int,Item> itemDic = new Dictionary<int,Item>();

Where the key is the itemID, and the Item is the Item. This way I have a sort of database to give it some itemID, and it spit back out the appropriate item. The issue is, if I add the class Tool to this dictionary, if I try accessing the dictionary value, it will not give access to the Tool variables (since the dictionary only specifies the top-level "item" class).

If I create several different inherited classes, how would I setup a dictionary to allow me to get the correct class / Type of item, out of the dictionary based on its itemID?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    `if (item is Tool) { ((Tool)item).toolDurability = 42; }` – GSerg Jan 05 '19 at 09:46
  • What's the point of having abstraction (Item) if you still have to access specific properties? This looks like bad design. – FCin Jan 05 '19 at 09:49
  • Possible duplicate of [Storing derived classes in a base class Dictionary](https://stackoverflow.com/questions/38137073/storing-derived-classes-in-a-base-class-dictionary) – GSerg Jan 05 '19 at 09:54

1 Answers1

2

You could do the following,.

For input,

Dictionary<int,Item> itemDict = new Dictionary<int,Item>
{
  [1] = new Item(){itemID = 2},
  [2] = new Tool(){itemID=3, toolDurability=4}
};

You can

foreach(KeyValuePair<int, Item> entry in itemDict)
{

  switch(entry.Value)
  {
    case Tool tool:
      Console.WriteLine(tool.toolDurability);
      break;
    case Item item:
      Console.WriteLine(item.itemID);
      break;
   }
 }
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51