user35443
user35443

Reputation: 6413

Error while trying to call method

I have this code:

var work = new DynamicMethod("work", null, Type.EmptyTypes);
            var il = work.GetILGenerator();
            il.Emit(OpCodes.Ldstr, "a");
            il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[]{typeof(string)}));
            var d = (Action)work.CreateDelegate(typeof(Action));
            d();

I'm just trying to create new method via System.Reflection.Emit. But it throws me this error:

Common Language Runtime detected an invalid program.

Does anybody know how must I repair it to working or where's error? Please help.

Upvotes: 2

Views: 97

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726649

I think that you are missing a call that emits return:

il.Emit(OpCodes.Ldstr, "a");
il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[]{typeof(string)}));
il.Emit(OpCodes.Ret);

Upvotes: 4

Related Questions