Tuesday, April 6, 2010

How to select multiple values in an enum

Lets say you have an enum called DaysOfWeek, because you need to keep track of multiple days a user may select, because they may select different combos of days. The most efficient to store this is by using an enum with [Flag] attribute.

Like this:













Notice the values are are 2^x. This is because this is actually an 8-bit field.
We have [0000000], with a bit for each day.

So lets say you have Monday and Saturday chosen. This would be:
[1000010] = 64 + 2 = 66

Ok so how do you use this value?

First we need to STORE the values. We do this by using a bitwise OR.
Example: if we chose Monday and Wednesday we have Monday = [10] and Wednesday = [1000]. ORing these together 10 | 1000 = 1010, which in decimal is 10.

Next we need to LOAD the values. We do this by using a bitwise AND.
Example: To see if Monday was chosen we would do the total bit representation [1010] AND Monday [10] so 1010 & 10, which will return [10], which in this case is Monday.

No comments:

Post a Comment

There was an error in this gadget