I am building a dynamic method using reflection. Most tutorials and documentation (e.g. How to: Define and Execute Dynamic Methods or Creating method dynamically, and executing it) show a very simple example.
I trying to find a way to reference another assembly from the dynamic assembly.
For example, I would like to be able to construct the following function by using Reflection.Emit.
public static void f(int n)
{
int[] arr = new arr[n];
return arr.Max();
}
What would be the common way of doing this?
The most reliable way to get valid IL instructions is to create your code in a high level language, compile it and decompile it. Next you can recreate the instructions with
Reflection.Emit.I changed your example function otherwise its not good testable because the result would be always the same:
Build as debug, ILDasm gives us (Release would result in far fewer instructions but there is not too much to see then):
Now you can recreate every aspect of this method with the MethodBuilder/DynamicMethod and the ILGenerator.
Test it:
and it should work: