Reflection Emit, what's the use?

4

Passing a code to MVC, I saw that there was a Label label= new Label(); that was underlined with red, when clicking to see the suggestions, I saw the following:

using System.Web.Ui.WebControls

using System.Reflection.Emit 

I was wondering what the Reflection Emit is for?

I saw some things on the net, mostly on the MS website, but I could not understand the use of it.

    
asked by anonymous 07.07.2014 / 18:00

1 answer

6

This is rarely used. The "normal" programmer will probably never use it.

Essentially it serves to create an Assembly of CIL . That is, it generates the "machine code" of the .NET virtual machine. It's a simplified way to create low-level code. He is concerned with putting together the appropriate format so that a machine code is understood by .NET.

In this way you can create arbitrary code at runtime to be written to a DLL (an assembly file) or to run immediately afterwards. Be it to create some functionality that can only be mounted at run time even, or to get a greater optimization.

  • The LINQ , for example, makes a lot of use of it to assemble your expression trees.
  • Serialization also wont use it.
  • Proxy object creation uses this feature.
  • Some situations language does not support some feature that can only be achieved by issuing low level code by passing the top level language.
  • Dapper is one of the many ORMs that use this issue.

Its use is intense in a compiler or some tool ( AOP and < Mockers are examples) to change the bytecode of the application developed for .Net (or any other compatible implementation, such as Mono, of course).

Now it's even less necessary. In most cases it is more interesting to use the services of the new compiler named .Net Compiler Platform (former Roslyn project) available in C # 6 / Visual Studio 2015. Generating code at runtime is much easier and more powerful in most cases.

Official Information Source .

Namespace .

    
07.07.2014 / 18:23