2

I have a Enum with Flags like this:

[Flags]
public enum ItemType
{
    Shop,
    Farm,
    Weapon,
    Process,
    Sale
}

Then I have several objects in a list with some flags set and some flags not set. It looks like this:

public static List<ItemInfo> AllItems = new List<ItemInfo>
{
        new ItemInfo{ID = 1, ItemType = ItemType.Shop, Name = "Wasserflasche", usable = true, Thirst = 50, Hunger = 0, Weight = 0.50m, SalesPrice = 2.50m, PurchasePrice = 5,  ItemUseAnimation = new Animation("Trinken", "amb@world_human_drinking@coffee@female@idle_a", "idle_a", (AnimationFlags.OnlyAnimateUpperBody | AnimationFlags.AllowPlayerControl)) },
        new ItemInfo{ID = 2, ItemType = ItemType.Sale, Name = "Sandwich", usable = true, Thirst = 0, Hunger = 50, Weight = 0.5m, PurchasePrice = 10, SalesPrice = 5, ItemUseAnimation = new Animation("Essen", "mp_player_inteat@pnq", "intro", 0) },
        new ItemInfo{ID = 3, ItemType = (ItemType.Shop|ItemType.Process), Name = "Apfel", FarmType = FarmTypes.Apfel, usable = true, Thirst = 25, Hunger = 25, Weight = 0.5m, PurchasePrice = 5, SalesPrice = 2, ItemFarmAnimation = new Animation("Apfel", "amb@prop_human_movie_bulb@base","base", AnimationFlags.Loop)},
        new ItemInfo{ID = 4, ItemType = ItemType.Process, Name = "Brötchen", usable = true, Thirst = -10, Hunger = 40, Weight = 0.5m, PurchasePrice = 7.50m, SalesPrice = 4}
}

Then I go trough the list with a loop and ask if the flag ItemType.Shop is set or not, like this:

List<ItemInfo> allShopItems = ItemInfo.AllItems.ToList();
foreach(ItemInfo i in allShopItems)
{
    if (i.ItemType.HasFlag(ItemType.Shop))
    {
        API.consoleOutput(i.Name);
    }
}

This is the output of my loop - it shows all items in the list, and the .HasFlag method always returns true in this case.

Wasserflasche
Sandwich
Apfel
Brötchen
Dennis Larisch
  • 563
  • 4
  • 19

2 Answers2

7

Try to assign values to your enum

[Flags]
public enum ItemType 
{
    Shop = 1,
    Farm = 2,
    Weapon = 4,
    Process = 8,
    Sale = 16
}

Here are some Guidelines for FlagsAttribute and Enum (excerpt from Microsoft Docs)

  • Use the FlagsAttribute custom attribute for an enumeration only if a bitwise operation (AND, OR, EXCLUSIVE OR) is to be performed on a numeric value.
  • Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. This means the individual flags in combined enumeration constants do not overlap.
Black Frog
  • 11,595
  • 1
  • 35
  • 66
CodeReaper
  • 775
  • 2
  • 6
  • 21
4

You should assign values to your enums. All the flags attribute does is change how the ToString method works. I would use a bitwise operator to make it less likely to make a mistake:

[Flags]
public enum ItemType
{
    Shop = 1 << 0, // == 1
    Farm = 1 << 1, // == 2
    Weapon = 1 << 2, // == 4
    Process = 1 << 3, // == 8
    Sale = 1 << 4 // == 16
}
Henrik
  • 23,186
  • 6
  • 42
  • 92
nelsontruran
  • 514
  • 4
  • 18