Automatically Generating Dynamic Enumerations

| No Comments | No TrackBacks

I use a product from Developer Express called XtraGrid.  It has some pretty remarkable features, one of which is a “flags” editor.

Say for instance that I have a bit flag enumeration:

public enum ColorFlags {
    Red = 1,
    Green = 2,
    Blue = 4

Now, if I want that to show up in my grid with a popup for a field like the following:


I have to do something very simple..


The DevExpress tools will enumerate over the enumeration (ha!) and gather all of the appropriate values, create the checked list edit, and display it to the user.  When the user finishes their edit, they are left with the numerical value of the bitwise operation.

That’s all and well, but what if my enumerations are stored in a database ?  I simply can’t use the .SetFlags method by itself, because there is no hard-coded enumeration to pull from!

What I needed to do was to create the enumeration dynamically, at runtime, to pull the information from the database and construct a dynamic enum.

Here is the code I created:

public enum FlagsType {
    Color = 1,
    Size = 2
private Type GenerateEnumerations(FlagsType f) {
    string asmNameString = String.Empty;
    switch(f) {
        case FlagsType.Color:
            asmNameString = "flags_color";
        case FlagsType.Size:
            asmNameString = "flags_size";
    //    Create Base Assembly Objects
    AppDomain appDomain = AppDomain.CurrentDomain;
    AssemblyName asmName = new AssemblyName(asmNameString);
    AssemblyBuilder asmBuilder = appDomain.
DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run); // Create Module and Enumeration Builder Objects ModuleBuilder modBuilder = asmBuilder.
DefineDynamicModule(asmNameString + "_module"); EnumBuilder enumBuilder = modBuilder.
DefineEnum(asmNameString, TypeAttributes.Public, typeof(int)); // Query the database for the value of the flags enumerations using (lsDataContext dbObj = new lsDataContext()) { var enumerations = (from j in dbObj.flags_mainTable where j.type == (int)f orderby select j).ToList(); foreach (flags_mainTable fmtObj in enumerations) enumBuilder.DefineLiteral(, fmtObj.flag); } return enumBuilder.CreateType(); }


Now I simply use the .SetFlags method, but this time like this:


I doubt this sort of scenario crops up often, but if it does I

hope this helps!


Matthew MacSuga

No TrackBacks

TrackBack URL:

Leave a comment

About this Entry

This page contains a single entry by Matthew M. published on January 29, 2009 2:47 PM.

OMG WOW! was the previous entry in this blog.

LINQ-to-SQL – Love it, or Hate It is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.