- Home /
Get class from an array of a base class with derived classes
Hi! So I have made an inventory system that stores items in a base class array (Item) which can have more classes that derive from it (Sword, Armor..). I tried (for testing) doing "Sword test = items[0] as Sword;" which works, but how do I know what class is in that array, since in this test I already knew that item 0 is a sword?
Answer by thePeine · Jun 21, 2017 at 12:51 AM
If you want to get a string representation, you can call items[0].GetType().ToString(), which will return you the full type as a string, but that's of little value for more than debugging. Usually, you'll just have a large if block, something like the following.
if(items[0] is Sword) {
Sword test = items[0] as Sword;
}
Or, if you actually want the type to display, it would probably be best to add a field to your base class, something like Description, that you can just hard code in each derived class.
"Or, if you actually want the type to display, it would probably be best to add a field to your base class, something like Description, that you can just hard code in each derived class."
This is essentially what I do. But ins$$anonymous$$d of a string, I create an enum that defines all the derived types, and return the enum value in a virtual property that is overridden in each derived class.
Your answer

Follow this Question
Related Questions
Check/compare array elements 1 Answer
Is it faster to access an Vector3 array than to access a mesh's vertices? 2 Answers
Problems with Arrays 2 Answers