Using Reflection.Emit to create a class implementing an interface

karma picture karma · Oct 30, 2009 · Viewed 17k times · Source

I need to generate a class using Reflection.Emit that implements the following interface.

public interface IObject
{
    T Get<T>(string propertyName); 
}

Does anyone have an example of how I would emit the following as a simple test case?

class GeneratedObject : IObject
{
    public T Get<T>(string propertyName)
    {
        // this is the simplest possible implementation
        return default(T);
    }
}

Answer

Nicole Calinoiu picture Nicole Calinoiu · Oct 30, 2009

If you're using Reflection.Emit, you really ought to grab a copy of the Reflection.Emit language add-in for Reflector. While not perfect, it should get you at least 95% of the way to any given emitted code.