// Define a new type TypeBuilder typeBuilder = moduleBuilder.DefineType("MyClass", TypeAttributes.Public); // Define a new constructor ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor( MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(string) } ); // Generate MSIL code to set the value of a field ILGenerator il = constructorBuilder.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Stfld, fieldBuilder); // Return from the constructor il.Emit(OpCodes.Ret); // Create an instance of the new class Type type = typeBuilder.CreateType(); object instance = Activator.CreateInstance(type, "Hello world");
ILGenerator il = methodBuilder.GetILGenerator(); Label trueLabel = il.DefineLabel(); Label endLabel = il.DefineLabel(); // Load the arguments onto the stack il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); // Compare the arguments il.Emit(OpCodes.Ceq); // Branch if the comparison is true il.Emit(OpCodes.Brtrue, trueLabel); // The comparison was false il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Br, endLabel); // The comparison was true il.MarkLabel(trueLabel); il.Emit(OpCodes.Ldc_I4_1); // End of the method il.MarkLabel(endLabel); il.Emit(OpCodes.Ret);Overall, the System.Reflection.Emit ILGenerator Call package library in C# provides developers with a powerful tool for generating and manipulating MSIL code at runtime.