Is it possible to store different subclasses in one array? C#
Im trying to make my own inventory system in C#. What I want to do is have a single Generic List of all the items in the game. However, not all items have the same variables, obviously, and I think subclassing is the way to go. However, I cannot figure out how to store all the items with their separate values into preferably one array.
A simple demonstration of what I want to do:
public class BaseItem{
public string name = "";
}
public class Weapon : BaseItem{
public int damage = 10;
}
public class Potion : BaseItem{
public int hpRestore = 50;
}
public List<?????> GameItems = new List<?????>();
GameItems.Add(new Weapon());
GameItems.Add(new Potion());
Is there any way to achieve this? All I have ended up with so far is errors and variables not appearing. Any directional help is welcome.
Answer by jgodfrey · Jun 21, 2016 at 10:45 PM
You should be able to store them as a collection of a common base class. So...
var GameItems = new List<BaseItem>();
GameItems.Add(new Weapon());
GameItems.Add(new Potion());
Though, to access specific properties of each derived class, you'll have to cast an element in your GameItems collection to the the specific type you're after...