Why do you need to emit IL code?

I work in a code base that is quite large, and today I found a project that emitted IL code inside a regular class .

The project containing the emitted IL code is an implementation of the Service Locator MSDN Desctiption .

What are the benefits of this and why would it be done as shown in C# ?

+4
source share
2 answers

This is usually done to circumvent overhead when using reflection, using information available only at run time.

Then you would use reflection, which can be slow depending on what you are doing, to create a new piece of code that works directly with the data provided to it, without using reflection.

Benefits:

  • Performance

Disadvantages:

  • Hard to debug
  • Hard to get right
  • It's hard to read the code after
  • Steep learning curve

Therefore, you need to make sure that it is really worth the price before proceeding with this.

Please note that this is a general answer. In the specific case that you are faced with, there is no way to answer the question of why this was done and what specific advantages (or disadvantages) you might have without seeing the code.

+12
source

There are many uses for this.
One of the most commonly used scenarios is changing / entering code on the fly:
.NET CLR Injection: change IL code at runtime


A good tutorial to help me understand what’s good for him: Dynamic ... But quick: a story about three monkeys, wolves and the DynamicMethod and ILGenerator classes


Good luck.

+2
source

Source: https://habr.com/ru/post/1494270/


All Articles