blue18hutthutt
blue18hutthutt

Reputation: 3243

Can I add a dynamic method to an existing type using System.Reflection.Emit?

I just started learning the Emit namespace - is the following valid? This throws an exception:

public class EmitTest
{
    public void Test()
    {
        DynamicMethod dynMeth = new DynamicMethod("Foo", null, null, typeof(EmitTest));
        ILGenerator gen = dynMeth.GetILGenerator();
        gen.EmitWriteLine("Foo");
        gen.Emit(OpCodes.Ret);
        dynMeth.Invoke(null, null);
        dynamic d = this;
        d.Foo();
    }
}

Is there anyway to make this work as intended or is it a limitation of DLR? Here I've created a new void method Foo() and created it as a member of the EmitTest class. The runtime says Foo() is not found on EmitTest

Upvotes: 0

Views: 519

Answers (1)

SLaks
SLaks

Reputation: 887453

You're misunderstanding the owner parameter.
MSDN says: (emphasis added)

owner

A Type with which the dynamic method is logically associated. The dynamic method has access to all members of the type.

You cannot add methods to an existing type.

Upvotes: 3

Related Questions