Home > Back-end >  How can I use Enum in switch statement
How can I use Enum in switch statement

Time:02-01

What I am trying to do is detecting the type of "item" and using it inside of a switch statement and based on that, choosing correct equipment slot. My code:

    public EquipmentSlot WeaponSlot;
    public EquipmentSlot ChestplateSlot;
    public EquipmentSlot LeggingsSlot;
    public EquipmentSlot HelmetSlot;

    public void EquipItem(Item item)
    {
        EquipmentSlot chosenSlot = null;
        
        switch(item.type)
        {
            case item.type.weapon:
                chosenSlot = WeaponSlot;
                break;
            case item.type.chestplate:
                chosenSlot = ChestplateSlot;
                break;
            case item.type.leggings:
                chosenSlot = LeggingsSlot;
                break;
            case item.type.helmet:
                chosenSlot = HelmetSlot;
                break;
        }

        chosenSlot.EquippedItem = item;
    }

Item class:

    public enum Type
    {
        weapon,
        chestplate,
        leggings,
        helmet
    }
    public Type type;

This error is showing up: error CS0176: Member 'Item.Type.helmet' cannot be accessed with an instance reference; qualify it with a type name instead (four times for each case in switch)

CodePudding user response:

Instead of case item.type.weapon: it should be case Item.Type.weapon:

CodePudding user response:

try this

switch (item.type)
    {
        case Type.weapon:
            chosenSlot = WeaponSlot;
            break;
        case Type.chestplate:
            chosenSlot = ChestplateSlot;
            break;

        .....
    }

but it will be much more readable if you rename Type to ArmoryType for example

  •  Tags:  
  • Related