James Ray Anderson

James Ray Anderson
James Ray Anderson
0 comments

Using Flags and Bitwise Operators for Storing Settings

12:38 PM
Many times there comes a design in which you have a single numeric database column for which you need to store multiple values. Using "Bitwise Operators" and an "Enumeration" can help you get the job done quickly and efficiently.

Sample Scenario
  • Your GUI has 5 checkboxes for various settings.
  • [ ] Created
  • [ ] Updated
  • [ ] Deleted
  • [ ] Renamed
  • These could all be on, or any combination thereof.
  • You need to store it in an int column in your database
  • More settings may be added in the future
Step 1: Create EnumerationCreate an enumeration of type Flags. The following sample show you how to do it. Each value starts with one and then is double for each subsequent additional setting. An all setting is a bitwise "or" of the previous settings. You could make various other combinations as well.
[Flags] private enum EventsToWatchFor: int{
Created = 1,
Updated = 2,
Deleted = 4,
Renamed = 8,
All = Created Updated Renamed Deleted
}

Step 2: Use the & Operator to EvaluateAssume you get a value from the database and you need to de-construct it and place checkmarks in the appropriate checkboxes. I won't go into how you get the data value, but we will assume it is in a variable called val with a value of 5. A value of 5 is essentially a "Create" orred with a "Delete".
if (((EventsToWatchFor)val & EventsToWatchFor.Created) == EventsToWatchFor.Created)
{
chkCreated.Checked = true;
}
You could tighten up the code and do it like this:
chkCreated.Checked = ((EventsToWatchFor)val & EventsToWatchFor.Created) == EventsToWatchFor.Created;

0 comments:

 
Toggle Footer
Top