Real world uses of Reflection.Emit

Ryu picture Ryu · Feb 22, 2010 · Viewed 19.3k times · Source

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.

Answer

Marc Gravell picture Marc Gravell · Feb 22, 2010

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).