4

There is a way to check if I got a flag in a series of flag?

Example:

[Flags]
Enum TestEnum
{
  ALIVE, DEAD, ALMOSTDEAD, HURT, OTHERS

}
// check if is alive and has been hurt
TestEnum aTest = TestEnum.ALIVE | TestEnum.HURT
bool aTest2 = aTest.HasFlag(TestEnum.ALIVE)

But a.Test.HasFlag always returns true, even without the TestEnum.ALIVE

LarsTech
  • 80,625
  • 14
  • 153
  • 225
Stickly
  • 311
  • 1
  • 2
  • 13

5 Answers5

13

You can certainly use Enum.HasFlag like everyone has suggested. However, its important to make sure that your enumeration falls in powers of two. Powers of two have a single bit set, so your enumeration should look like this:

Enum TestEnum
{
    ALIVE = 1, DEAD = 2, ALMOSTDEAD = 4, HURT = 8, OTHERS = 16
}

The reason this is important is because you are comparing the bit flags. In memory, your enum flags will look like this:

ALIVE      = 00001
DEAD       = 00010
ALMOSTDEAD = 00100
HURT       = 01000
OTHERS     = 10000

When you do a bitwise compare, like DEAD | ALMOSTDEAD, you are doing this:

DEAD       = 00010
           OR
ALMOSTDEAD = 00100
------------------
RESULT     = 00110

Since the Result is > then 0, its true.

Icemanind
  • 47,519
  • 50
  • 171
  • 296
  • 4
    A easy way to do the powers of two when assinging them is to use the `<<` operator. `Enum TestEnum { ALIVE = 1<<0, DEAD = 1<<1, ALMOSTDEAD = 1<<2, HURT = 1<<3, OTHERS = 1<<4 }` – Scott Chamberlain Oct 18 '13 at 21:20
1

If you want to use this as FLAGS I believe your declaration is wrong. Check out this previous post. Because of the default incrementing, HasFlag won't work as you expect unless you set the values to powers of 2.

What does the [Flags] Enum Attribute mean in C#?

Community
  • 1
  • 1
Carth
  • 2,303
  • 1
  • 17
  • 26
0

I think you are making a game, so you should make a class for this issue

public class Player
{
    bool isAlive;
    bool isHurt;
...
}

Later you could check your states like this:

if (player.isAlive && player.isHurt)
{
 //dosomething
}
user1567896
  • 2,398
  • 2
  • 26
  • 43
0

You can do bitwise operation like this:

var alive = TestEnum.Alive;
var hurt = TestEnum.Hurt;
var aliveAndHurt = alive & hurt;
rageit
  • 3,513
  • 1
  • 26
  • 38
-1

You can use Enum.HasFlag to check for this.

bool aTest2 = aTest.HasFlag(TestEnum.ALIVE);
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373