Using C# generics to extract enumerated flags from a numeric value

.NET, ASP.NET 2.0, Technical stuff, Website
See comments
I posted a new page on my site, demonstrating how to use generics to extract enumerated flag values from an integer value in a generic way. I wrote this utility class, because I wanted a way to execute actions on the server using a URL query parameter sent from the client.
Until now, when I wanted to execute an action, I was using a URL like:
Then I was mapping the value 3 to an enum value, and would execute the corresponding action before rendering the page. (for example, converting data to XML files used by the page, etc...). However, with this way I was only able to execute one action per roundtrip only. Also, it was not generic.
To solve that, I am writing a class deriving from System.Web.UI.Page, which I intend to make the base class for most ASPX pages on my site. This new GalaSoftLb.Web.CustomControls.CPage class will contain methods and definitions used by all the derived pages. In the case we're discussing, it allows using a query string parameter "actions", which can contain any numeric value. Let's say for example that I have:
public enum EPageActions
  eCleanUp = 1,
  eConvertDataToXml = 2,
  eCreateLogFile = 4,
  eDoSomethingElse = 8,
  eRenderPageToHtml = 16,
Using this enum, I can tell my page to perform a clean-up, then convert some data to XML and then do something else before rendeing just by using the URL:
(because 1 + 2 + 8 = 11)
To extract the values corresponding to EPageActions (or to any other enum for that matter), I wanted to have a generic utility class, and of course it was a good excuse to use generics ;-)
The CFlagsExtracter<T> class takes two parameters: An enumeration type and an integer value (Int32). The enumeration value must be a bit field (aka set of flags). This is ensured by the presence of a FlagsAttribute.
By the way, checking if a given flag is set in an integer value is very easy when you know how: Make a logical (bitwise) AND between the integer value and the flag value. This will set all the other bits to 0. After that, compare the resulting value with the flag value, et voilà :-)
int iFlagValue = (int) EPageActions.eConvertDataToXml;
int iTest = ( iFlagValue & iNumericValue );
if ( iTest == iFlagValue )
  // The flag "eConvertDataToXml" is set in iNumericValue
More info about CFlagsExtracter, including a (AJAX powered!) demo and the source code
Previous entry | Next blog entry

Comments for Using C# generics to extract enumerated flags from a numeric value