Search code examples
c#.net-3.5reflection.emit

Reflection.Emit and Instantiation


I have an assembly and some classes. What I'm trying to do is create an instance of a class and fill its properties in a generic way, something like:

public T FillObject(IDictionary<string,object> values)
{
    /// CREATE INSTANCE
    /// FILL THE PROPERTIES WITH THE VALUES
}

Reflection is the best way but its too slow, instead I've heard that Reflection.Emit is faster, so, is there a way to instantiate the class and fill its properties with Reflection.Emit?

Thanks in advance for any help.


Solution

  • On this occasion, I suggest HyperDescriptor; it is like reflection, but with IL generation thrown in the middle for performance; then, you just use regular component-model code:

    object obj = Activator.CreateInstance(typeof(T));
    var props = TypeDescriptor.GetProperties(typeof(T));
    foreach(var pair in data)
    {
        props[pair.Key].SetValue(obj, pair.Value);
    }
    

    Edit; for a bit of a 2012 update, FastMember involves less abstraction:

    var accessor = TypeAccessor.Create(typeof(T));
    foreach(var pair in data)
    {
        accessor[obj, pair.Key] = pair.Value;
    }
    

    In addition to being more direct, FastMember will work with properly dynamic types, too - not just reflection.