0

I followed this Q & A: Dynamic enum in C# and it works well, the best answer has code from this msdn article: EnumBuilder Class

This Dynamic Enum code generation works for one Enum in the DLL. The problem is when I attempt to add a second Enum it doesn't work, I can only access the first Enum "Elevation" from the referenced DLL.

How do I add two or more Enums to the DLL?

class Example
{
    public static void Main()
    {
        // Get the current application domain for the current thread.
        AppDomain currentDomain = AppDomain.CurrentDomain;

        // Create a dynamic assembly in the current application domain,  
        // and allow it to be executed and saved to disk.
        AssemblyName aName = new AssemblyName("TempAssembly");
        AssemblyBuilder ab = currentDomain.DefineDynamicAssembly(
            aName, AssemblyBuilderAccess.RunAndSave);

        // Define a dynamic module in "TempAssembly" assembly. For a single-
        // module assembly, the module has the same name as the assembly.
        ModuleBuilder mb = ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");

        // Define a public enumeration with the name "Elevation" and an 
        // underlying type of Integer.
        EnumBuilder eb = mb.DefineEnum("Elevation", TypeAttributes.Public, typeof(int));

        // Define two members, "High" and "Low".
        eb.DefineLiteral("Low", 0);
        eb.DefineLiteral("High", 1);

        // Create the type and save the assembly.
        Type finished = eb.CreateType();

        //-------------------------------------
        //HERE IS THE CODE TO CREATE A 2ND ENUM
        //-------------------------------------
        EnumBuilder eb1 = mb.DefineEnum("SecondEnum", TypeAttributes.Public, typeof(int));
        eb1.DefineLiteral("Bad", 0);
        eb1.DefineLiteral("Good", 1);
        Type SecondEnum = eb1.CreateType();

        ab.Save(aName.Name + ".dll");
    }
}
Community
  • 1
  • 1
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321

1 Answers1

1

Something odd is happening at work because I can do it at home. Ref TempAssembly in another project and I can access the SecondEnum:

using ProjectName;
...
private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show(SecondEnum.Good.ToString());
}

Update:

Turns out I was adding two values (numbers), not a key and a value.

SecondEnum.DefineLiteral("Must Be Alphanumeric", Convert.ToInt32(dr[0].ToString()));

Update 2:

Make sure the Enum doesn't start with a space!!

Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321