Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add multiple objects to a single array?

Tags:

arrays

c#

object

I am designing a very simple inventory system for a game. I have run into an obstacle where I have the inventory (an array of a specific type) that would need to accept multiple types of objects. My code:

IWeapon[] inventory = new IWeapon[5];

public void initialiseInventory(IWeapon weapon, IArmour armour)
{
    inventory[0] = weapon; // Index 0 always contains the equipped weapon
    inventory[1] = armour; // Index 1 always contains the equipped armour
}

I would get an error stating that the array can't convert the armour object to a weapon object (which is the array type). I then thought I might make a superclass (well, interface to be precise) that IWeapon and IArmour would inherit from. But then I run into another error...

IItem[] inventory = new IItem[5];

public void initialiseInventory(IWeapon weapon, IArmour armour)
{
    inventory[0] = weapon; // Index 0 always contains the equipped weapon
    inventory[1] = armour; // Index 1 always contains the equipped armour

    Console.WriteLine("The weapon name is: " + inventory[0].Name) // Problem!
}

Since the array type is IItem, it would only contain properties and methods from IItem, and not from IWeapon or IArmour. Thus the problem came in that I could not access the name of the weapon located in the subclass (subinterface) IWeapon. Is there a way I could redirect it somehow to look for properties in a subinterface (IWeapon or IArmour) rather than the superinterface (IItem)? Am I even on the right path?

like image 625
Frapie Avatar asked Dec 04 '22 12:12

Frapie


1 Answers

Since the first item will always be a weapon, and the second will always be armor, you shouldn't use an array (or any data structure) at all. Just have two separate fields, one that holds a weapon and another an armor instance.

private IWeapon weapon;
private IArmour armor;

public void initialiseInventory(IWeapon weapon, IArmour armour)
{
    this.weapon = weapon;
    this.armor = armor;
}
like image 54
Servy Avatar answered Dec 22 '22 02:12

Servy