Confused about Flags() attribute

  • Thread starter Thread starter Joel Moore
  • Start date Start date
J

Joel Moore

Say I have an enum similar to this:

<Flags()> Enum TestFlags As Short
One = 0
Two = 1
Three = 2
Four = 4
End Enum

I figured I could declare variable of type TestFlags to be used in the
following way:

Dim test As TestFlags

test = TestFlags.One Or TestFlags.Three

However when I check the value of test it is equal to TestFlags.Three
rather than the combined value.

Additionally, if I explicitly set test = 3 (for example), I am unable to
determine which bits are set (I tried using "test = TestFlags.Two" and
"test And TestFlags.Two")

What point am I missing here?

Joel Moore
 
Joel,
Try the following:
<Flags()> Enum TestFlags As Short None = 0
One = 1
Two = 2
Three = 4
Four = 8
End Enum

When I am using Flags, I reserve the number 0 for no flags set, then I use
1, 2, 4, 8, 16... for each specific flag. With VB.NET 2003 (.NET 1.1) you
can use:
<Flags()> Enum TestFlags As Short None = 0
One = 1 << 0
Two = 1 << 1
Three = 1 << 2
Four = 1 << 3
End Enum

You need to use And to check for individual flags, something like:

If (test And TestFlags.Two) = TestFlags.Two Then
' Two is set
End If

If (test And TestFlags.Three) = TestFlags.Three Then
' Three is set
End If

Hope this helps
Jay
 
Joel said:
Say I have an enum similar to this:

<Flags()> Enum TestFlags As Short
One = 0
Two = 1
Three = 2
Four = 4
End Enum

Shouldn't it be:
<Flags()> Enum TestFlags As Short
One = 1
Two = 2
Three = 4
Four = 8
End Enum

Cheers

Arne Janning
 
Joel Moore said:
Say I have an enum similar to this:

<Flags()> Enum TestFlags As Short
One = 0
Two = 1
Three = 2
Four = 4
End Enum

I figured I could declare variable of type TestFlags to be used in the
following way:

Dim test As TestFlags

test = TestFlags.One Or TestFlags.Three

However when I check the value of test it is equal to TestFlags.Three
rather than the combined value.
fyi - thats correct - 'one' is say 0000 and 'three' which equals 2 is 0010 the 'Or' of
which gives you 0010 which is in fact TestFlags.Three (2)
Additionally, if I explicitly set test = 3 (for example), I am unable to
determine which bits are set (I tried using "test = TestFlags.Two" and
"test And TestFlags.Two")

What point am I missing here?
as Jay pointed out - for this you'll need to use the 'And' operator..
 
check out the FlagsAttribute class (system.FlagsAttibute)
this helps you use an enum as a block of bit flags, aternatively have a look at the BitVector strucure (System.Collections.Specialized.BitVector32)

hth

guy
 
Back
Top