Not so long ago I started to learn to use System.Reflection.Emit namespace. I’m now trying to translate this code to use of ILGenerator:
MyClass c = new MyClass("MyClass");
c.Do(":D");
For this piece of code I have three questions: how to create object? how to call contructor and how to call method of class? Please help.
Here’s a complete example that shows the necessary IL code.
You can test this in LINQPad:
Output:
Incidentally, you can use LINQPad to get hold of the IL code for a particular example. Let me cut out the IL-part of the above example, like this (I removed the class as well, it’s the same class):
By executing this code, and then using the IL tab of the output, you can see the generated code:
The two instructions
stloc.0andldloc.0is the variable in the code.The IL I emitted first is akin to this piece of code:
ie. no variable, just temporary storage on the stack, and indeed: