Using Flag Enumerations for “On/Off” Features
{ January 10th, 2008 }
When it comes to some of our package features in ConceptShare we found it much easier to use a flag enumeration to test if a particular package had a given feature enabled such as SSL, custom branding, etc.
Flag enumerations behave very similar to a standard enumeration just that it allows usage of bitwise operations to “test” if a particular value is selected. Flag enumerations basically work off of the powers of 2. Below is a sample enumeration (C#.NET):
[System.Flags()]
public enum PFlags
{
None = 0,
SSL = 1,
CustomBranding = 2,
PaidAccount = 4,
All = SSL | CustomBranding | PaidAccount
}
So you have the enumeration, let’s write a few little wrapper classes to make it easy to “Set” flags, and also “Check” flags.
public Boolean IsFlagSet(PFlags flags, PFlags flagItem)
{
return ((flags & flagItem) == flagItem);
}
public PFlags SetFlagOn(PFlags flags, PFlags flagItem)
{
return (flags | flagItem);
}
public PFlags SetFlagOff(PFlags flags, PFlags flagItem)
{
if ((flags & flagItem) == flagItem)
flags ^= flagItem;
return flags;
}
That is all there is too it. You don’t have to use the helper functions and you can write the code inline but I find this easier as I sometimes forget which bit-wise operator I should be using. I won’t go into the theory of how flag enumerations work as there are many comprehensive articles available online. Below are some samples on how to use the functions.
// Enumeration with SSL & Custom Branding Set;
PFlags f = PFlags.SSL | PFlags.CustomBranding;
// Checks if SSL is enabled (returns true);
Boolean result = IsFlagSet(f, PFlags.SSL);
// Sets Custom Branding Off
f = SetFlagOff(f, PFlags.CustomBranding);
If you enjoyed this post, make sure you subscribe to our web feed!
Categories: Development ~ ~ Trackback

Leave a Reply