4

I am trying to add a new class into an assembly with 1 method call that I am trying to call from elsewhere in this assembly. Currently I have the following:

ParameterDefinition param = new ParameterDefinition("Param", ParameterAttributes.None, mod.Import(typeof(string)));
Collection<Instruction> methodInstructions = new Collection<Instruction>();
methodInstructions.Add(Instruction.Create(OpCodes.Ldarg_0));
methodInstructions.Add(Instruction.Create(OpCodes.Ret));
MethodDefinition newMtd = MethodCreator.CreateMethod("ExampleMethod", mod, methodInstructions, param, typeof(string));
// Lets add the new method to the module entrypoint declaring type
TypeDefinition Class = new TypeDefinition("MyNamespace", "MyNewClass", TypeAttributes.Class);
mod.Types.Add(Class);
Class.Methods.Add(newMtd);

This creates the new method and class as expected and this can be seen in .net reflector. All that this method does it return the parameter being passed (which is the expected result). I am trying to call this method using the following code:

public void InsertCalls(MethodDefinition methodToInsertCallsTo, MethodDefinition methodToCall)
{
    ILProcessor ilp = methodToInsertCallsTo.Body.GetILProcessor();
    for (int i = 0; i < methodToInsertCallsTo.Body.Instructions.Count; i++)
    {
        if (methodToInsertCallsTo.Body.Instructions[i].OpCode == OpCodes.Ldstr)
        {
            Instruction loadString = methodToInsertCallsTo.Body.Instructions[i];
            ilp.InsertAfter(loadString, Instruction.Create(OpCodes.Call, methodToCall));
        }
    }
}

So all this does is insert a call to the method I created every time the Ldstr opcode is encountered. This insertion works fine but when the method is called I get this error in the assembly I've inserted these calls into:

System.TypeLoadException: Could not load type . from assembly WinFormsTest because the parent does not exist.

Does anyone have any ideas on what could be causing this?

user3412625
  • 99
  • 1
  • 8

1 Answers1

3

An old question, but here's the answer:

Newly-constructed TypeDefinitions have their BaseType prop set to null, which is invalid for classes. Try setting it to TypeSystem.Object instead.

Jason Holloway
  • 682
  • 5
  • 9