Home > Blockchain >  Why is my enum comparison not finding the proper value?
Why is my enum comparison not finding the proper value?

Time:06-11

I am trying to find a specific Enum from a list of objects. Here is the code:

foreach (IEquipment equipment in EntityEquipmentList)
{
     CapabilityEnum equipmentCapability = equipment.Capability;
     this.JammerLabel.Text  = "\nEquipment Found "   equipment.Name   equipmentCapability;
                           
     if (equipmentCapability.Equals(CapabilityEnum.Jammer))
     {
          this.JammerLabel.Text  = "\nJAMMER FOUND "   equipment.Capability;
          Form1 SUCCESSFORJAMMER = new Form1();
          SUCCESSFORJAMMER.Show();                     
     }
}

Just to be clear, EntityEquipmentList is a List of IEquipment objects and I am trying to find the one that has "Jammer" as it's capability. As you can see in the "if" statement, I am comparing the capability (which is of the type "CapabilityEnum") of my piece of equipment to that of the Enum of Jammer.

I will attach the Enum below just for ease of reference, in case it is important.

public enum CapabilityEnum : long
{
    CustomBits = -281474976710656,
    Flare = -2147483648,
    All = -1,
    None = 0,
    TDL_JREAP_A = 1,
    SubSurface = 2,
    Surface = 4,
    Air = 8,
    Space = 16,
    Sensor = 32,
    Weapon = 64,
    Active = 128,
    Detection = 256,
    Tracking = 512,
    Guidance = 1024,
    Command = 2048,
    Illuminator = 4096,
    EarlyWarningRadar = 32768,
    HeightFindingRadar = 65536,
    AcquisitionRadar = 131072,
    Optical = 262144,
    Radio = 524288,
    Jammer = 1048576,
    Radar = 2097152,
    Sonar = 4194304,
    TDL_Link16 = 8388608,
    TDL_EPLRS_SADL = 16777216,
    IFF = 33554432,
    TDL_C2_IADS = 67108864,
    TDL_GATEWAY = 134217728,
    TDL_IDM = 268435456,
    TDL_C2_SAM = 536870912,
    Chaff = 1073741824
}

As you can see Jammer is in the middle with the value "1048576". To be honest this is my first time working with Enum's, so any help is appreciated.

And to be clear, I am 100% certain that there is a piece of Equipment in the list with the Capability of Jammer.

CodePudding user response:

Note that the values in your capabilities enum are "powers of two" (1, 2, 4, 8, ... instead of 1, 2, 3, 4, ...). This is usually done for flag enums, where an enum value can be a combination of different defined values. For example, an equipment could have the capability of Jammer as well as Radar.

Well, now Jammer Radar (or, to be precise: Jammer | Radar, using bitwise OR) is not equal to Jammer, which is why your comparison fails. You can fix this by using HasFlag instead of Equals:

if (equipmentCapability.HasFlag(CapabilityEnum.Jammer)) { ... }

In addition, you should add the Flags attribute to your enum. This

  • documents the fact that these enum values can be combined, and also
  • causes equipmentCapability.ToString() to output Jammer, Radar instead of the numerical value.
  • Related