Please see the code below:
Public Class Form1
<Flags> _
Public Enum Days
Monday = 0
Tuesday = 1
Wednesday = 2
End Enum
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim s As String = (Days.Monday Or Days.Tuesday).ToString()
End Sub
End Class
The value of s becomes: Tuesday. I would expect it to be: Monday,Tuesday as per Thomas Levesque's answer here: FlagsAttribute what for?.
What am I doing wrong?
UPDATE After Jon Skeets answer I have tried this:
<Flags> _
Public Enum Days
None = 0
Monday = 1
Tuesday = 2
Wednesday = 4
End Enum
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim s As String = (Days.Monday And Days.Tuesday).ToString()
End Sub
However, 's' now equals 'NONE'? Also is there any logic in the sequence of numbers i.e. 0,1,2,4,8 etc or could I use 0,1,2,3,4 etc.
What am I doing wrong?
You're giving Monday
a value of 0, which means it's irrelevant when you perform a bitwise-OR.
The only sensible semantic value of 0 in a Flags
-based enum is None
.
You should have:
<Flags> _
Public Enum Days
None = 0
Monday = 1
Tuesday = 2
Wednesday = 4
Thursday = 8
...
End Enum
Note that aside from the "none" value I've included, that's the same as the values given in the post you referred to. The values are important! They're effectively what gets stored... the names are just useful for us as humans.
EDIT: Now you've updated your code, you've changed the operator from Or
to And
, so you're performing a bitwise AND of 1 and 2... which is 0. To be additive, you need to use Or
.
And yes, the sequence of numbers is precisely bitwise, doubling each time: 1, 2, 4, 8, 16, 32 etc. The "none" value of 0 is just "no bits set". I suggest you read the FlagsAttribute
documentation carefully.
See more on this question at Stackoverflow