Managing object collections using a switching declaration

advertisements

I need to have a player equip an item as shown here:

IEquiptable is an interface.

and this method is in my in player class.

public void equip(IEquiptable equipable)
    {
        switch (equipable.GetType())
        {
            case equipable is Weapons:
                this.weapon = equipable;
                break;

            case equipable is Shield:
                this.shield = equipable
                break;

                //etc etc..
        }
    }

I get an error that the switch experession must be a bool,char,string,integral, enum or corresponding nullable type.

I could handle it by having an equit method in each of my weapon/shield etc classes and pass over my player class as a parameter. But I feel this is slightly illogical as a player should equipt an item, not an item equip it's self on the player.


You already have an interface so why don't you make use of it?

public interface IEquipable
{
    void EquipOn( Player player );
}

public class Shield : IEquipable
{
    public void EquipOn( Player player )
    {
        player.shield = this;
    }
}

public class Weapons : IEquipable
{
    public void EquipOn( Player player )
    {
        player.weapon = this;
    }
}

and your code becomes

public void equip(IEquiptable equipable)
{
   equipable.EquipOn( this );
}

In fact, you don't even need this method, as it has been reduced to merely forwarding its job to proper class. Everytime you have your IEquipable you just call its EquipOn method.