How and when does .NET really compile code?

Say you are writing an application in C #, VB, something with .NET. When you click build, does it really compile your code? I thought so until I started using the redgates reflector on some of my builds and saw my code verbatim. I would expect the loops to be rolled out and one more set of optimizations, not nothing.

So when does compilation happen? I think that when it is built, the code will become IL (Intermediary Language), and when this happens, it loads into the CLR? Is it optimized only with CLR and never during build?

+4
source share
2 answers

When compiling in VS

  • The source code is compiled into byte code, known as Common Intermediate Language (CIL) or MSIL (Microsoft Intermediate Language).
  • Metadata from each class and all methods (and everything else: O) is included in the PE header of the resulting executable file (be it dll or exe).
  • If you create an executable, the PE header also includes the usual bootable media, which is responsible for loading the common language runtime (CLR) when executing the executable.

By doing:

  • The bootstraster initializes the CLR (mainly by loading the mscorlib assembly) and instructs it to complete your assembly.
  • The CLR performs the master record.
  • Now classes have a vector table in which the addresses of the method functions are stored, so when MyMethod is called, this table is executed, and then the corresponding call to the address is made. After starting, ALL records for all tables have a JIT compiler address.
  • When a call to one of these methods is executed, the JIT is called instead of the actual method and takes control. JIT then compiles the CIL code into the actual assembly code for a suitable architecture.
  • After compiling the code, the JIT goes to the method vector table and replaces the address with one of the compiled code, so that each subsequent call no longer calls JIT.
  • Finally, JIT handles the execution of compiled code.
  • If you call another method that has not yet been compiled, go back to 4 ... and so on ...

I also leave the answer here, since the other question was not quite about that ...

+16
source

It compiled before IL, well, compilation time. The magic of the reflector is that it "understands" IL and converts it back to C # (or VB.NET or something else). Look at the Options menu in Reflector, and you can view the assembly in any format, including IL).

In Reflector, you actually don't see your source code. You see the translation of IL in C #. In most cases, it will be very similar to what you wrote, but there are some telltale signs - for example, find the place where you implemented the auto-property :

string MyProperty {get;set;} 

And you will see what actually compiles, something like this:

 public string MyProperty { [CompilerGenerated] get { return this.<MyProperty>k__BackingField; } [CompilerGenerated] set { this.<MyProperty>k__BackingField = value; } } 
+3
source

All Articles