Returning derived classes from Item database using Polymorphism

So I have class a basic class Hierarchy: Item, Weapon and Commodity. Weapon inherits Item and Commodity inherits Item as well.

I have a database class that stores Items in the dictionary. This item database class has a GetItem method that returns an Item based on it’s id. I need to set values to a Weapon by accessing the ItemDatabase for example. I can’t just cast (Weapon) after GetItem has returned me an Item, that would give me an InvalidCastException.

So my question is: How do i make a method that returns a Weapon or Commodity by giving it the id of the item?

Well once you get the Item back, you need to determine what type of class is it. The most basic form would be:

if(item is Weapon)
      Weapon weaponFromItem = item as Weapon;

Here we check if the item is a weapon(literally verbatim) and if it is, it will be safe to cast into a Weapon. The reason you get errors is because the cast is failing when it tries to cast a Item that is a Commodity into a Weapon. The direct cast ie: (Weapon)item is also valid in the above example but the “as” cast is the safe cast and generally a good practice to follow.