views:

445

answers:

11

In all the books I've read on reflection they often say that there aren't many cases where you want to generate IL on the fly, but they don't give any examples of where it does make sense.

After seeing Reflection.Emit as a job requirement for a gaming company I was curious where else it's being used.

I'm now wondering if there are any situations you've seen in the real world were it was the best solution to the problem. Perhaps it is used as an implementation to a design pattern?

Note I imagine PostSharp / AOP uses it.

+2  A: 

I'm using it as a way to create dynamic proxies on the fly to wrap a class. NHibernate uses this same pattern to proxy calls to POCO objects to instead query a database.

Any time you want to be able to "write code" (i.e. create a new function, etc.) dynamically, you'll need Emit.

David Pfeffer
That used to be more true before the System.Linq.Expressions namespace came into play with the `Compile()` method.
280Z28
Woah that's awesome. Thanks for pointing that out to me.
David Pfeffer
I should add that some phantom bugs silently resolved themselves when I switched some Emit code to Expressions code. It's cleaner and more maintainable for basically every place it applies to.
280Z28
A: 

Duck Typing

Yuriy Faktorovich
Interesting.. where would it make sense to use Duck Typing?
Ryu
+1  A: 

The XMLSerializer actually generates code and compiles it on first run. You can read this great blog post on Scott Hanselman's site regarding how to debug XML Serialization if you know this is happening.

Nick
The post suggest that XMLSerializer actually generates C# code and compiles it instead of emitting IL directly.
Daniel Brückner
I corrected my post, it now says generates IL
Ryu
+2  A: 

The DLR and DLR related languages heavily rely on Reflection.Emit

JaredPar
+2  A: 

Castle DynamicProxy uses it for, you guess, dynamic proxies. DynamicProxy is then used by the Castle's IoC container Windsor and OR mapper ActiveRecord.

Daniel Brückner
...and Rhino Mocks and Moq and NHibernate and whole set of other frameworks and applications ;)
Krzysztof Koźmic
A: 

Mocking libraries also use Reflection.Emit to generate proxies used in Unit Testing.

Nick
+1  A: 

Dynamically generating a mock object which implements some interface. Example frameworks which do this: moq, rhino mocks.

Wim Coenen
+1  A: 

I remember seeing Relection.Emit used in chapter 8: "On-the-Fly Code Generation for Image Processing" of Beautiful Code. Basicly the author specializes a function for doing a certain set of image processing operations on a given image, which in turn leads to greatly reduced execution time.

Mads Ravn
+1  A: 

Expression.Compile essentially does this - that is key to some of LINQ.

I am currently using reflection emit to re-write a serialization API - because sometimes reflection just isn't good enough. As it happens this will also allow it to generate dlls (much like how sgen works), allowing fully static code (I'm hopeful this will make it iPhone friendly).

I also use a similar approach in HyperDescriptor to provide very fast name-based property-lookup.

I've also used emit to do things like:

all related to SO questions.

Finally, this IL approach is the core of protobuf-net "v2"; the reason here is that it allows me both to have a fast model at runtime (compiling it via IL on the fly), and to write the same directly to a static-compiled dll, so that it works on things like iPhone, Phone 7, etc (which lack the necessary meta-programming APIs).

Marc Gravell
@Marc: could you please provide the links to those questions you mention?
Jordão
@Jordão - added
Marc Gravell
A: 

I have recently used it to create a proof of concept for compiling a set of operations that's very expensive to do at runtime, and achieved a 200% improvement in speed. The operations were to use RegEx to parse a large string, and loop over the matches, use Reflection to find and instantiate types, and a bunch of other things that aren't exactly fast. By using IL emit, I created dynamic functions that matched a delegate type (using DynamicMethod) and cached them. I did the normal RegEx/Reflection dance once per input value to figure out what it should do, then used StringBuilder to concatenate the strings as literals, and instead of Reflection/Activator I now could use the actual types themselves in the emitted IL. Here's a helpful tip: don't try to write IL yourself unless you're a sado-masochist. Write a sample function or type in C# that does what you want, compile it, and use Reflector or ILDASM to see the generated IL. Then use Emit to do similar logic. Another tip is you can create locals and store them to variables, then use Emit(OpCodes.Ldloc, myLocalVar) and it'll get the local address for you, instead of having to keep track of the local index (i.e. ldloc_1).

Paul
A: 

I've used it in an application where a property had to be accessed repeatedly via reflection (because the property name was not known at compile time).

By creating a helper class at runtime that generates code to access the property, the resulting code was an order of magnitude faster than the original reflection-only code.

Philippe Leybaert
I just wrote a library to do this, but it use `Expression` trees instead of `Reflection.Emit`.
Gabe