The question is answered, right answer was accepted
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?
Answer by landon912 · Apr 04, 2016 at 12:55 PM
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.
Yeah i was already doing that, got some ItemType id's incorrectly in the database file, now it works.
Follow this Question
Related Questions
C# Abstract methods with default parameters 1 Answer
Make a virtual method englobing a child override function 0 Answers
How can i get component as an abstract base class? 1 Answer
Decorator Design Pattern - Not extending object behavior 1 Answer
RPG Picking up items with polymorphism - probably quick :) 1 Answer