IL Invalid program, can't understand why

c#, reflection.emit

Solution

Before you can store values in a local, you must declare the local using the `ILGenerator.DeclareLocal` method. Referring to locals that don't exist will cause the JIT compiler to declare the program invalid.

Problem

I'm emitting some IL, here my code: ``` mgen.Emit(OpCodes.Ldc_I4,0); mgen.Emit(OpCodes.Newarr, typeof(object)); mgen.Emit(OpCodes.Stloc_1); // THIS SHOULD mgen.Emit(OpCodes.Ldloc_1); // MATCH THIS ONE mgen.Emit(OpCodes.Callvirt, typeof(IInternalFactory).GetMethod("Create")); mgen.Emit(OpCodes.Castclass, method.ReturnType); mgen.Emit(OpCodes.Ret); ``` This is a work in progress, I've create an array, and now I'm preparing to do somethings with it, so I decided to store it ( Stloc_1 ) and then push it back onto the stack (Ldloc_1) as soon I did these instruction the IL is signaled to be invalid, but if I understood correctly, these instruction should leave the stack unmodified. Without these two instruction the IL works perfectly. So I can't unserstand why a pop with a subsequent push does not work.

Original source