16

I've come across dynamic methods a little in reflection-based C# code, and I'm yet to figure out precisely what they are. There specifically seems to be a DynamicMethod class that allows the generation and specification of CLR methods at runtime. But then there's also the MethodBuilder class. They both seem to do very similar things. Apparently "dynamic assemblies" are AssemblyBuilder classes and "dynamic types" are TypeBuilder classes. They all reside in the System.Reflection.Emit namespace in any case.

MSDN seems to have precious little high-level information on this subject. So if someone could explain what dynamic methods are, where exactly all the XYZBuilder classes come into play here, and what they're each used for, that would be great. Any other Reflection.Emit types and functionality I should know about would be appreciated too.

Noldorin
  • 144,213
  • 56
  • 264
  • 302

1 Answers1

18

I think the documentation for DynamicMethod explains this well:

You can use the DynamicMethod class to generate and execute a method at run time, without having to generate a dynamic assembly and a dynamic type to contain the method. The executable code created by the just-in-time (JIT) compiler is reclaimed when the DynamicMethod object is reclaimed. Dynamic methods are the most efficient way to generate and execute small amounts of code.

If you need to dynamically create one or more methods, use DynamicMethod. If you want to create whole types, it means you need to create a dynamic assembly (AssemblyBuilder), then create a module inside it (ModuleBuilder) and then create one or more types (TypeBuilder). To create methods inside those types, you would use MethodBuilder.

Another difference is GC: DynamicMethods can be always garbage collected and they are collected one by one. That is, any method can be collected as soon as you stop using it. Dynamic assemblies, on the other hand, can be collected only when you specify it (by using AssemblyBuilderAccess.RunAndCollect) and they are always collected assembly by assembly. For example, if you have two types in an assembly, and you use only one of them, the other one can't be collected.

svick
  • 236,525
  • 50
  • 385
  • 514