Reputation: 2596
I have an enum to represent two states, and I wanted to create combinations. After doing some reading this morning I came across the flags attribute. I understand that if you go up by the power of 2 each time then the binary values only have one bit set so combinations are possible.
<Flags()> _
Public Enum TaskStatus
Incomplete = 1
Complete = 2
End Enum
1 = 0000001
2 = 0000010
so a combination of 1+2 would be 0000011
I would like to then construct a database paramater to indicate which states, if any, had been chosen. What would be the best way to do this? Im guessing I cant just send the binary to my sp, but am not sure.
I also don't understand how the flags would work if you had more than 7 values in the enum?
Upvotes: 3
Views: 150
Reputation: 3290
Why 7 values? A standard integer is 32 bits long. You could use a long for 64 bits. And if it is a 64 bit application, you could have a 128 bit long. If you don't care about readability inside the database, there is no reason you cant just store the value as an int or bigint in your database.
Furthermore, it will be easier to keep the powers of 2 up if you express your values in HEX:
Value1 = 0x1
Value2 = 0x2
Value3 = 0x4
Value4 = 0x8
Value5 = 0x10
Value6 = 0x20
To insert each value individually into your database, you would create an integer field for each flag in your database and then when you insert do this:
flag1 = (int)flagEnumValue & (int) flagEnum.Value1
flag2 = (int)flagEnumValue & (int) flagEnum.Value2
That is a bitwise and, which you can read about here
Upvotes: 2