Creating a method with Reflection.Emit, and then invoking it
.net, c#, dynamic, reflection, reflection.emit
Solution
If you are creating individual method(s), then `DynamicMethod` is a much better choice (especially since your method is static) - you just use`CreateDelegate` (specifying the delegate type), cast to that delegate, and invoke. It is also less overhead, and collectible.
But if you are forced to use `MethodBuilder`: you must use `CreateType` on the `TypeBuilder`, then use reflection on the now real type (returned from `CreateType`).
Problem
This sounds like such an obvious thing but I am having a lot of difficulty. Basically, what I'm doing is generating a method using Reflection.Emit and I then want to call it. So far, I have the method building and such, but I can't get a reference to the method after it's built because "The invoked member is not supported before the type is created." Here is what I basically do: ``` AssemblyBuilder assembly; ModuleBuilder module; TypeBuilder containerTypeBuilder; Type containerType; var name = new AssemblyName(); name.Name = "DynamicWrapper"; var domain = Thread.GetDomain(); assembly = domain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave); module = assembly.DefineDynamicModule(assembly.GetName().Name, false); containerTypeBuilder = module.DefineType("__DynamicWrapperType", TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout, typeof(object)); //build method var mb = containerTypeBuilder.DefineMethod("generatedmethod" + (unique++), MethodAttributes.Public | MethodAttributes.Static, typeof (int), new Type[] {}); //build method body and all that ..... var type=module.GetType("__DynamicWrapperType"); var info=type.GetMethod(mb.Name, BindingFlags.Static | BindingFlags.Public); //error here ``` How do I take my freshly built method and load it up so that I can invoke it? Also, I've tried `mb.Invoke`, but that yields "The invoked member is not supported in a dynamic module."