I'm trying to learn how If statements are generated with ILGenerator in C#.
Here's my code: (ilg is an ILGenerator)
ilg.Emit(OpCodes.Ldc_I4_1);
Label start = ilg.DefineLabel();
ilg.Emit(OpCodes.Brfalse, start);
ilg.Emit(OpCodes.Ldstr, "Hello");
ilg.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
ilg.MarkLabel(start);
Some notes:
- Alone, calling Console.WriteLine works perfectly.
- This is the error that I get when I run the generated exe:
Unhandled Exception: System.InvalidProgramException: Common Language Runtime detected an invalid program. at Testing.Test.Main(String[] )
You code works almost fine, you just forgot to put
OpCodes.Retat end, see the code that works:Then you'll have this output
If you comment this line
ilGenerator.Emit(OpCodes.Ret);you will get this exceptionRemember, every method in C# must have the OpCode.Ret
If your Main method is empty, like this
The IL generated (in debug mode, without optimization) will be this
The IL generated (in release mode, with optimization) will be this