1
enum Type{
   Monster = 1 << 0,
   Human = 1 << 1,
   Boss = 1 << 2,
}

Type unit = Type.Mosnter | Type.Boss;

Type eSearch = Type.Monster | Type.Human | Type.Boss;

Debug.Log((eSearch & unit) != 0);  // True
Debug.Log(eSearch.HasFlag(unit))   // True

eSearch = Type.Monster | Type.Human;

Debug.Log((eSearch & unit) != 0);  // True
Debug.Log(eSearch.HasFlag(unit))   // False

I want to know in detail why the first and second result values are different when using the above code.

HasFlag seems to make a perfect comparison, so please tell me what bit operations (such as '&') are internal actions.

Ps. I understand the first and second '&' operations.

Thank you for reading.

DevSon
  • 51
  • 6
  • 2
    Your comparison is wrong: should be `(eSearch & unit) != unit` which correctly returns false. `!= 0` semantically means: are *any* of the bits in `unit` present in `eSearch`, whereas you want: are *all* the bits present – Charlieface Sep 03 '21 at 00:22
  • 1
    eSearch.HasFlag(unit) equals to eSearch & unit == unit – dexiang Sep 03 '21 at 00:28
  • Thank you, everyone. I understand! Have a nice day today :-) – DevSon Sep 03 '21 at 00:41
  • 1
    The version using the bitwise AND operator may be preferrable, because `HasFlag` requires boxing: https://stackoverflow.com/questions/11665279/why-enums-hasflag-method-need-boxing – Klaus Gütter Sep 03 '21 at 04:56
  • @KlausGütter That's a good point. So i want use bit operator, but i have no idea.... If you don't mind, could you look at my new question? https://stackoverflow.com/questions/69039700/c-sharp-flagenum-generic-usage?noredirect=1#comment122017919_69039700 – DevSon Sep 03 '21 at 05:01

1 Answers1

2

HasFlag seems to make a perfect comparison

Yes. It checks if the enum value has all of the values present in the argument. According to the documentation, the bit operation performed is:

thisInstance And flag = flag

In other words, eSearch.HasFlag(unit) is the same as:

(eSearch & unit) == unit

It's checking whether the AND is exactly the same as unit, not just non-zero.

Side note: you should also add the [Flags] attribute to your Type enum:

[Flags]
enum Type {
    ...
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Oh, well, let me get this is... 1. Complete comparison of all desired bits on: (eSearch & unit) == unit 2. Some comparisons to check that any bit is On: (eSearch & unit) != 0 Is this right? – DevSon Sep 03 '21 at 00:39