12

Given the enum:

[Flags]
enum foo
{
a = 1,
b = 2,
c = 4
}

then

foo example = a | b;

If I don't know if foo contains c, previously I have been writing the following

if (example & foo.c == foo.c)
    example  = example ^ foo.c;

Is there a way to do this without checking for the existance of foo.c in example?

As when it comes to additions, I can just do an OR, and if the enum value already exists in example then it doesnt matter.

maxp
  • 24,209
  • 39
  • 123
  • 201

2 Answers2

26

I think you want:

example &= ~foo.c;

In other words, perform a bitwise "AND" mask with every bit set except the one for c.

EDIT: I should add an "except" to Unconstrained Melody at some point, so you could write:

example = example.Except(foo.c);

Let me know if this would be of interest to you, and I'll see what I can do over the weekend...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
9

AND it with the complement of foo.c:

example = example & ~foo.c
Sjoerd
  • 74,049
  • 16
  • 131
  • 175