When you use the MethodBuilder.SetImplementationFlags(System.Reflection.MethodImplAttributes) method in combination with the erload:System.Reflection.Emit.MethodBuilder.SetCustomAttribute method, be aware of potential interactions. For example, using the erload:System.Reflection.Emit.MethodBuilder.SetCustomAttribute method to add the System.Runtime.InteropServices.DllImportAttribute attribute also sets the System.Reflection.MethodImplAttributes.PreserveSig flag. If you subsequently call the MethodBuilder.SetImplementationFlags(System.Reflection.MethodImplAttributes) method, the System.Reflection.MethodImplAttributes.PreserveSig flag is overwritten. There are two ways to avoid this:
Call the MethodBuilder.SetImplementationFlags(System.Reflection.MethodImplAttributes) method before you call the erload:System.Reflection.Emit.MethodBuilder.SetCustomAttribute method. The erload:System.Reflection.Emit.MethodBuilder.SetCustomAttribute method always respects existing method implementation flags.
When you set implementation flags, call the MethodBuilder.GetMethodImplementationFlags method to retrieve the existing flags, use bitwise OR to add your flag, and then call the MethodBuilder.SetImplementationFlags(System.Reflection.MethodImplAttributes) method.