MSIL IF Statement
This example shows you how to generate IL for a simple IF statement
Code in C#
int x = 1000;
if (x > 2000)
Console.WriteLine("Hey There");
Using Reflection Emit
AssemblyName _assemblyName = new AssemblyName();
_assemblyName.Name = "ifS";
AssemblyBuilder _assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(_assemblyName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder _modBuilder = _assemblyBuilder.DefineDynamicModule(_assemblyName.Name + ".exe", true);
TypeBuilder _typeBuilder = _modBuilder.DefineType("IfType");
MethodBuilder _methodBuilder = _typeBuilder.DefineMethod("Main", MethodAttributes.Static, typeof(void), System.Type.EmptyTypes);
ILGenerator _il = _methodBuilder.GetILGenerator();
LocalBuilder _intName = _il.DeclareLocal(typeof(int));
Label body = _il.DefineLabel();
_il.Emit(OpCodes.Ldc_I4, 1000);
_il.Emit(OpCodes.Stloc_0);
_il.Emit(OpCodes.Ldloc_0);
_il.Emit(OpCodes.Ldc_I4, 2000);
_il.Emit(OpCodes.Blt, body);
_il.Emit(OpCodes.Ret);
_il.MarkLabel(body);
_il.EmitWriteLine("Hey there");
_il.Emit(OpCodes.Ret);
_typeBuilder.CreateType();
_modBuilder.CreateGlobalFunctions();
_assemblyBuilder.SetEntryPoint(_methodBuilder, PEFileKinds.ConsoleApplication);
_assemblyBuilder.Save(_assemblyName.Name + ".exe");
_il = null;
Code in C#
int x = 1000;
if (x > 2000)
Console.WriteLine("Hey There");
Using Reflection Emit
AssemblyName _assemblyName = new AssemblyName();
_assemblyName.Name = "ifS";
AssemblyBuilder _assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(_assemblyName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder _modBuilder = _assemblyBuilder.DefineDynamicModule(_assemblyName.Name + ".exe", true);
TypeBuilder _typeBuilder = _modBuilder.DefineType("IfType");
MethodBuilder _methodBuilder = _typeBuilder.DefineMethod("Main", MethodAttributes.Static, typeof(void), System.Type.EmptyTypes);
ILGenerator _il = _methodBuilder.GetILGenerator();
LocalBuilder _intName = _il.DeclareLocal(typeof(int));
Label body = _il.DefineLabel();
_il.Emit(OpCodes.Ldc_I4, 1000);
_il.Emit(OpCodes.Stloc_0);
_il.Emit(OpCodes.Ldloc_0);
_il.Emit(OpCodes.Ldc_I4, 2000);
_il.Emit(OpCodes.Blt, body);
_il.Emit(OpCodes.Ret);
_il.MarkLabel(body);
_il.EmitWriteLine("Hey there");
_il.Emit(OpCodes.Ret);
_typeBuilder.CreateType();
_modBuilder.CreateGlobalFunctions();
_assemblyBuilder.SetEntryPoint(_methodBuilder, PEFileKinds.ConsoleApplication);
_assemblyBuilder.Save(_assemblyName.Name + ".exe");
_il = null;
Comments