Search code examples
c#reflectionreflection.emit

Reflection.Emit better than GetValue & SetValue :S


I've been told to use Reflection.Emit instead of PropertyInfo.GetValue / SetValue because it is faster this way. But I don't really know what stuff from Reflection.Emit and how to use it to substitute GetValue and SetValue. Can anybody help me with this ?


Solution

  • Just an alternative answer; if you want the performance, but a similar API - consider HyperDescriptor; this uses Reflection.Emit underneath (so you don't have to), but exposes itself on the PropertyDescriptor API, so you can just use:

    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj);
    props["Name"].SetValue(obj, "Fred");
    DateTime dob = (DateTime)props["DateOfBirth"].GetValue(obj);
    

    One line of code to enable it, and it handles all the caching etc.