Why emitting IL?

Apr 17, 2013 at 10:23 AM
I'm learning the code of Unity1.2, and found in the process of resolving a object, a plan will be built dynamically by emitting IL and then the executed to get the object.

Since I'm not very familiar with Unity, why emitting IL is used here instead of a static method implementation? Any benefits?

Apr 18, 2013 at 11:34 AM
There are only four ways (that I know of) of creating new instances of a class:
  1. Calling new() (which is not an option if you need a generic solution that includes calling non-default ctors).
  2. Activator.CreateInstance(...) which has a big impact on performance if you use it frequently.
  3. Expressions (which can also emit IL under the covers and are a PITA to build).
  4. IL which looks nasty (but reduces the danger that people will start throwing it at every problem).
Emitting IL code was there before Expressions became a part of the framework. I think I saw a post somewhere that states that IL will be replaced with Expressions in Unity 3.0
Apr 25, 2013 at 5:34 AM
I would guess the main reason would have been performance.

As an aside, two other ways to create an object would be deserialization and calling Invoke on a ConstructorInfo object.

Randy Levy
Enterprise Library support engineer
Support How-to