Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Bitwise complement operator with [Flags] attribute on C# enum

0 views
Skip to first unread message

Michael Marshall

unread,
Nov 18, 2002, 11:41:17 PM11/18/02
to
For c# enumerations with the [Flags] attribute, it is clear to me that
they can be combined with the bitwise OR operator (|). But, how does
one remove a flag from an enumeration variable, I have tried the
obvious:

[Flags]
public enum myEnum
{
One,
Two,
Three
}

...

// to add flags
myEnum m = myEnum.One | myEnum.Two;

// to remove myEnum.Two (? doesn't work)
m &= ~myEnum.Two;


m ends up being zero after these steps.

Any ideas?
Mike

Jason Smith

unread,
Nov 19, 2002, 12:23:50 AM11/19/02
to
Let's rewrite that enumeration the way .NET sees it, and the problem should
be clear:
public enum myEnum
{
One = 0,
Two = 1,
Three = 2
}


First, you had better make those "flags" binary. Otherwise you cannot
combine them using binary operators. Well, you can, but what you get is
unusable.

public enum myEnum
{
Flag1 = 1,
Flag2 = 2,
Flag3 = 4,
Flag4 = 8
}

Since the original value of One was 0, and the original value of Two was 1,
then you got exactly what you should get when you do the operations you
outlined. Use the enumeration above and things will work correctly.

"Michael Marshall" <Mpl...@yahoo.com> wrote in message
news:b0c50f08.02111...@posting.google.com...

Michael Marshall

unread,
Nov 20, 2002, 9:03:04 AM11/20/02
to
What is the benefit of using the [Flags] attribute then? Isn't there
an assymetry in the implementation of enums when the bitwise AND (&)
operator works with the [Flags] attribute and &= does not?

Mike

"Jason Smith" <jsm...@hotmail.com> wrote in message news:<#yr$Xv4jCHA.2408@tkmsftngp11>...

0 new messages