How to translate the creation of a new object?
Not too long ago, I started learning how to use the System.Reflection.Emit namespace. Now I am trying to translate this code to use ILGenerator:
MyClass c = new MyClass("MyClass");
c.Do(":D");
For this piece of code, I have three questions: How do I create an object? how to call contructor and how to call a class method? Please, help.
source to share
Here is a complete example that shows the required IL code.
You can check this in LINQPad :
void Main()
{
// Manual test first
MyClass c = new MyClass("MyClass");
c.Do(":D");
var method = new DynamicMethod("dummy", null, Type.EmptyTypes);
var il = method.GetILGenerator();
// <stack> = new MyClass("MyClass");
il.Emit(OpCodes.Ldstr, "MyClass");
il.Emit(OpCodes.Newobj, typeof(MyClass).GetConstructor(new[] { typeof(string) }));
// <stack>.Do(":D");
il.Emit(OpCodes.Ldstr, ":D");
il.Emit(OpCodes.Call, typeof(MyClass).GetMethod("Do", new[] { typeof(string) }));
// return;
il.Emit(OpCodes.Ret);
var action = (Action)method.CreateDelegate(typeof(Action));
action();
}
public class MyClass
{
public MyClass(string text)
{
Console.WriteLine("MyClass(" + text + ")");
}
public void Do(string text)
{
Console.WriteLine("Do(" + text + ")");
}
}
Output:
MyClass(MyClass)
Do(:D)
MyClass(MyClass)
Do(:D)
By the way, you can use LINQPad to get the IL code for a specific example. Let me strip out the IL part of the above example like this (I removed the class, and the same class):
void Main()
{
MyClass c = new MyClass("MyClass");
c.Do(":D");
}
By executing this code and then using the IL tab in the output, you can see the generated code:
Two commands stloc.0
and ldloc.0
is a variable in the code.
The IL emitted first is akin to this piece of code:
new MyClass("MyClass").Do(":D");
i.e. there is no variable, just temporary storage on the stack and indeed:
source to share