views:

184

answers:

1

I need to create a dynamic enum and then be able to get the type using Type.GetType(). Is this possible?

The below code will create a dynamic enum, and attempt to use it's qualifying name. This is fine if I first store the assembly (using AssemblyBuilderAccess.RunAndSave). However, this is not possible if I'm solely using AssemblyBuilderAccess.Run; a BindingFailure error occur; unable to find the assembly. My impression was that the Run option would allow creation and usage without having to actually store the assembly (or having access to the different Builders).

(Note: The below code usage of Type.GetType() is not mine. I cannot change that code.)

How can I, without storing the assembly, create a dynamic enum and reference it?

        private Type CreateType()
        {          
        // Define the assembly.
        System.Reflection.Emit.AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new System.Reflection.AssemblyName("temporaryAssembly"), AssemblyBuilderAccess.Run);

        // Actually create it.
        System.Reflection.Emit.ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("temporaryAssembly");

        // Create the enum.
        System.Reflection.Emit.EnumBuilder enumBuilder = moduleBuilder.DefineEnum("Temp", System.Reflection.TypeAttributes.Public, typeof(int));

        /* Populate the enum. */

                    return enumBuilder.CreateType();
        }

        private void DoStuff()
        {
                    Type t = CreateType();
                    Type createAnotherOfSameType = Type.GetType(t.AssemblyQualifiedName);
        }/
A: 

I don't understand what you're trying to do there. Two problems: 1) the second line is just trying to get a reference to the Type again, which will be the same reference as the first line; it's not an instance you're getting. 2) IIRC, AssemblyQualifiedName is null for an in-memory type/assembly.

-Oisin

x0n
The second line will be done in another assembly. I will pass 't' to the assembly which will later handle it, using that particular code. Above was just for illustrative purposes.
Fredrik Ullner
By the way, AssemblyQualifiedName actually return the (seemingly) correct information.
Fredrik Ullner