Question

I am developing a game with an inventory system in C#/XNA. My plan is for the inventory to store the base class, Item. Derived from Item is an Equipment class (and other classes). Derived from the Equipment class is a Gun class (and other classes). Item has an enum that contains its type (Equipment, Crafting, etc.) and the Equipment class has an enum that contains its type (Gun, Armor, etc.). Using the information from the type enums would it work when--dropping a Gun from the inventory into the world for instance--to cast from Item to Equipment, then from Equipment to Gun?

Was it helpful?

Solution

Yes

Casting doesn't change the nature of the object, just what you are "looking at it as". The cast will throw an InvalidCastException if it isn't actually of that type (or inherits from that type), so be careful when doing this.

You could instead use the as operator and check for null afterwards as a much safer way of casting. Either way, you can cast as much as you like and it won't cause any problems.

To try and explain why casting from Item to Gun is ok, think about it in pure English terms:

Say I hand you a bunch of Items. Those items are of many types, some of which are Guns. You pick an item at random (say its a Gun for arguments sake). You can safely treat it as an Item, a piece of Equipment, or a Gun. It doesn't matter which, as long as it actually is a gun. Of course, if you picked an apple, and tried to treat it as a gun, that could cause some problems (and hilarity :) ).

OTHER TIPS

I believe the question is this:

var someItem = new Gun() { ItemType = ItemTypes.Equipment, EquipmentType = EquipmentTypes.Gun };

//Later, after item is dropped, we know it is an Item only, do some fancy dynamic cast?
Item droppedItem = Drop(someItem);
var castItem = ((droppedItem.EquipmentType)(droppedItem.ItemType)droppedItem) //Can't do this

Unfortunately, it is not possible to do a dynamic cast at runtime in C#.

You're going to need something like:

if(droppedItem is Gun)
{
    DoSomethingWithAGun(droppedItem);
}

As others mentioned though, if you already know it is a Gun, then simply do:

Gun droppedGun = (Gun)droppedItem;
//Or
Gun droppedGun = droppedItem as Gun;

There are some differences between those two statements. See Direct casting vs 'as' operator?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top