0

If I want to check a combined value with enum value, I run following code (included there remarks)

    // 001 | 010 = 011.
    Enum1 firstAndSecond1 = Enum1.First | Enum1.Second;                                    
    // 011 | 000 = 011 == true but should be false!
    Console.WriteLine("None: {0}", (firstAndSecond1 | Enum1.None) == firstAndSecond1);
    
    // 0010 | 0100 = 0110.
    Enum2 firstAndSecond2 = Enum2.First | Enum2.Second;                                    
    // 0110 | 0001 = 0111 == false.
    Console.WriteLine("None: {0}", (firstAndSecond2 | Enum2.None) == firstAndSecond2);   
    
    public enum Enum1
    {
        None   = 0b_000,
        First  = 0b_001,
        Second = 0b_010,
        Third  = 0b_100,
        All    = 0b_111
    }
    public enum Enum2
    {
        None   = 0b_0001,
        First  = 0b_0010,
        Second = 0b_0100,
        Third  = 0b_1000,
        All    = 0b_1111
    }

The problem is if I assign Nonevalue as 0, the check is incorrect as it returns true, it only works if Nonevalue is set as 1 << 0

Should the None value always be set as power of two or am I missing something? Because, for example, looking at this topic: What does the [Flags] Enum Attribute mean in C#?, all None values start from 0in all examples - this is what is confusing me

Humble Newbie
  • 98
  • 1
  • 11
  • 3
    Your enums are not Flags enums – Tim Schmelter Mar 09 '23 at 16:57
  • 2
    A flags enum represents a number of different possibilities, more than one of which might be set at a time. So your enum can have the `First` flag set or cleared, and also independently have the `Second` flag set of cleared. `None` means that no flags are at all. You can't have an enum which has the `First` flag set, and also has no flag set (i.e. is `None`). You seem to be expecting `None` to behave the same as one of the other flags, so an enum can be both `None` **and** `First`. I think that's where the confusion is coming from. – canton7 Mar 09 '23 at 17:01
  • 1
    So, `None` should have the value `0`, because a value of `0` means that none of the bits are set (because if any bit was set, the value would be non-zero) – canton7 Mar 09 '23 at 17:02
  • 1
    (and by this token asking whether the enum has the bits `firstAndSecond2 | Enum2.None` set is a meaningless question, because an enum can't have both the `First` and `Second` bits set, **and also** have no bits set) – canton7 Mar 09 '23 at 17:08

0 Answers0