Is it possible to insert IL code to C# method?
I'll add my own tool to the list of solutions already provided here: InlineIL.Fody.
This uses the Fody assembly weaving tool to modify the assembly at build time. Which means all you have to do is install a NuGet package, add a config file to your project and you're done.
You're then provided with a simple and type-safe API to emit IL instructions, which you can mix with C# code. I believe it's easier to write IL in this way than writing text, and it's also more convenient than ILGenerator
since each opcode gets its own method with relevant overloads only.
Here's an example, with using static InlineIL.IL.Emit;
:
public static void ZeroInit(ref T value)
where T : struct
{
Ldarg(nameof(value));
Ldc_I4_0();
Sizeof(typeof(T));
Unaligned(1);
Initblk();
}
This shows how to access the initblk instruction which C# doesn't currently expose.