Click here to Skip to main content
11,408,708 members (61,897 online)
Click here to Skip to main content

Fast Dynamic Property/Field Accessors

, 4 Jul 2006
Rate this:
Please Sign up or sign in to vote.
Fast run-time access to Property/Field values using the new (.NET 2.0) DynamicMethod class, and a very small amount of emitted IL code.


Quite often, I run across the need to dynamically retrieve the value of an object's property (or field), where the actual member might not be known until run-time.

Some examples of where one might use this are:

  • Comparer for sorting an array/list/collection
  • Class to filter a collection based on member values
  • Class to serialize/deserialize a list of objects (faster than BinaryFormatter)


In the past, I have made use of run-time reflection to: find a property's PropertyInfo or a field's FieldInfo, and Invoke the GetValue method of the PropertyInfo or FieldInfo on an object to retrieve the value.

PropertyInfo pi = typeof(Widget).GetProperty("ID");
Int32 id = (Int32) pi.GetValue(widget, null);

This works fine if you only have to retrieve the member's value for a single object; but once you have to get the value in a loop, it performs very slow.

The New Method (.NET 2.0)

I got to thinking, why not generate (at run-time) the same IL code that the compiler generates at compile time, and use that to call the property's get accessor or retrieve the field's value?

In previous versions of .NET (1.0 and 1.1), there is a pretty big overhead to generating IL code. This is because using the System.Reflection.Emit namespace requires an out-of-process call to csc.exe to actually generate the IL Code.

Thankfully, .NET 2.0 provides us with a new DynamicMethod class, that is a much more light-weight method of generating IL code.

Using this new DynamicMethod class, it is easy to produce a fast method for dynamically retrieving member values.


GetID = TypeUtility<Widget>.GetMemberGetDelegate<Int32>("ID");
Int32 id = GetID(widget);

The Code

public class TypeUtility<ObjectType>
    public delegate MemberType 
           MemberGetDelegate<MemberType>(ObjectType obj);

    public static MemberGetDelegate<MemberType>
        GetMemberGetDelegate<MemberType>(string memberName)
        Type objectType = typeof(ObjectType);
        PropertyInfo pi = objectType.GetProperty(memberName);
        FieldInfo fi = objectType.GetField(memberName);
        if (pi != null)
            // Member is a Property...

            MethodInfo mi = pi.GetGetMethod();
            if (mi != null)
                // NOTE:  As reader J. Dunlap pointed out...
                //  Calling a property's get accessor is faster/cleaner using
                //  Delegate.CreateDelegate rather than Reflection.Emit 
                return (MemberGetDelegate<MemberType>)
                          MemberGetDelegate<MemberType>), mi);
                throw new Exception( String.Format(
                    "Property: '{0}' of Type: '{1}' does" + 
                    " not have a Public Get accessor",
                    memberName, objectType.Name ) );
        else if (fi != null)
            // Member is a Field...
            DynamicMethod dm = new DynamicMethod("Get" + memberName,
                typeof(MemberType), new Type[] { objectType }, objectType);
            ILGenerator il = dm.GetILGenerator();
            // Load the instance of the object (argument 0) onto the stack
            // Load the value of the object's field (fi) onto the stack
            il.Emit(OpCodes.Ldfld, fi);
            // return the value on the top of the stack

            return (MemberGetDelegate<MemberType>)
            throw new Exception( String.Format(
                "Member: '{0}' is not a Public Property or Field of Type: '{1}'",
                memberName, objectType.Name ));

Tweaking Performance - Caching the Generated Code

There is a small amount of build up time that occurs during each call to GetMemberGetDelegate. This is due to having to generate the IL code and create a delegate. If possible, the generated delegate should be kept around for future use. Below is the code that can be used for that purpose.

public class TypeUtility<ObjectType>
    private static Dictionary<string,Delegate>
    _memberGetDelegates = new Dictionary<string,Delegate>();

    public static MemberGetDelegate<MemberType> 
        GetCachedMemberGetDelegate<MemberType>(string memberName)
        if ( _memberGetDelegates.ContainsKey(memberName) )
            return (MemberGetDelegate<MemberType>) 

        MemberGetDelegate<MemberType> returnValue = 
             GetMemberGetDelegate<MemberType>( memberName );
        lock ( _memberGetDelegates )
            _memberGetDelegates[memberName] = returnValue;
        return returnValue;

Performance Test Results

Performance Test Screen Shot

Based on my performance tests, using the dynamically generated code is 30x-50x faster than using normal reflection. It is still only about half as fast as using compiled code, which I imagine is due to the number of method calls. With compiled code, there is only one method call: the property's get accessor. When using the run-time generated code, you end up making two method calls: first to the generated code, and second to the property's get accessor. Depending on your exact usage, you may be able to optimize further and get back to one method call.

An Example Using This Concept

I mentioned earlier that one example of where this concept could come in handy is in the case of a generic comparer used to sort a collection or a list.

Consider the following:

List<Widget> widgets = GetWidgetsListFromSomewhere();
// Sort widgets by ID
widgets.Sort( new MemberComparer<Widget>("ID") );
// Now re-sort widgets by Name
widgets.Sort( new MemberComparer<Widget>("Name") );

You can see how easy this makes it to sort your collection based on a dynamic property or field. For example, you could easily wire this up to a UI to allow for fast sorting based on the column a user clicked on.

Here is the code for a simple MemberComparer class:

Note: This could easily be extended to support chaining of fields and sort directions together.

public class MemberComparer<ObjectType> : IComparer<ObjectType>
    private delegate int CompareDelegate(ObjectType x, ObjectType y);
    private CompareDelegate _compare;

    public MemberComparer(string memberName)
        _compare = GetCompareDelegate(memberName);

    public int Compare(ObjectType x, ObjectType y)
        return _compare(x, y);

    private CompareDelegate GetCompareDelegate(string memberName)
        Type objectType = typeof(ObjectType);

        PropertyInfo pi = objectType.GetProperty(memberName);
        FieldInfo fi = objectType.GetField(memberName);
        Type memberType = null;
        bool isProperty = false;

        if (pi != null)
            if (pi.GetGetMethod() != null)
                memberType = pi.PropertyType;
                isProperty = true;
                throw new Exception(String.Format(
                    "Property: '{0}' of Type: '{1}' " + 
                    "does not have a Public Get accessor",
                    memberName, objectType.Name));
        else if (fi != null)
            memberType = fi.FieldType;
            throw new Exception(String.Format(
                "'{0}' is not a Public Field or Property" + 
                " with a Get accessor for Type: '{1}' ",
                memberName, objectType.Name));

        Type comparerType = 
          new Type[] { memberType });
        MethodInfo getDefaultMethod = 
        MethodInfo compareMethod = 

        DynamicMethod dm = 
           new DynamicMethod("Compare_" + memberName, typeof(int),
           new Type[] { objectType, objectType }, comparerType);
        ILGenerator il = dm.GetILGenerator();

        // Load Comparer<memberType>.Default onto the stack
        il.EmitCall(OpCodes.Call, getDefaultMethod, null);

        // Load the member from arg 0 onto the stack
        if (isProperty)
            il.EmitCall(OpCodes.Callvirt, pi.GetGetMethod(), null);

        // Load the member from arg 1 onto the stack
        if (isProperty)
            il.EmitCall(OpCodes.Callvirt, pi.GetGetMethod(), null);

        // Call the Compare method
        il.EmitCall(OpCodes.Callvirt, compareMethod, null);

        return (CompareDelegate)dm.CreateDelegate(

Assuming you want to sort the Widget class, the CompareDelegate that gets dynamically created contains the dynamic equivalent of the following code:

// To Sort by Name property
public int Compare(Widget x, Widget y)
 return System.Collections.Generic.Comparer<string>.Default.Compare(
                                                            x.Name, y.Name);
// To Sort by ID property
public int Compare(Widget x, Widget y)
 return System.Collections.Generic.Comparer<int>.Default.Compare(x.ID, y.ID);


There are many other places that this concept can be used in place of the old slow method of reflection. With this article, I have only scratched the surface of what can be done. Hopefully, I have at least given some insight into how powerful Reflection.Emit can be. I leave it up to the reader, however, to find other places that they might be able to use similar code and/or concepts.


  • 07/04/2006 - Updated code to also work with fields, and added a generic comparer example.
  • 06/23/2006 - Created initial version.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Stephen Erisman
Web Developer
United States United States
I am currently working as an Enterprise Architect at

I have been designing and developing web/windows based software applications and utilities for 8+ years.

And here is a random picture of my dog. Wink | ;)

Comments and Discussions

GeneralMy vote of 5 PinmemberakramKamal21-Oct-12 13:10 
Questionneed help for SetFieldDelegate PinmemberBib3477027-Nov-11 7:58 
GeneralMemberComparer and LINQ PinmemberAnthony Bouch29-Jun-08 3:58 
GeneralSmall addition to DynamicPropertyManager PinmemberAnastasiosyal22-Jun-07 3:25 
QuestionDynamic types? PinmemberMaidenGuy14-Jun-07 0:50 
AnswerRe: Dynamic types? PinmemberStephen Erisman15-Jun-07 12:17 
QuestionHow about Set PinmemberScottVB24-Apr-07 4:57 
GeneralCultureInfo aware MemberComparer class help PinmemberNikolaj Lynge Olsson28-Feb-07 11:34 
That MemberComparer class is awesome!

Any ideas on how to use it with CultureInfo as a parameter to the constructor?

The reflection way is rather simple, but I have no clue about the emit stuff Frown | :(

// Reflection way

private Comparer _comparer;

// constructor
if (cultureInfo == null)
_comparer = new Comparer(System.Globalization.CultureInfo.InvariantCulture);
_comparer = new Comparer(cultureInfo);

public int Compare(T x, T y)
Type t = x.GetType();
PropertyInfo val = t.GetProperty(_propertyName);
if (val != null)
return _comparer.Compare(val.GetValue(x, null), val.GetValue(y, null));
throw new Exception(_propertyName + " is not a valid...");

Any ideas?
NewsProblems with structs (and solved!) Pinmemberunbird16-Feb-07 3:58 
GeneralRe: Problems with structs (and solved!) PinmemberStephen Erisman16-Feb-07 12:06 
GeneralRe: Problems with structs (and solved!) Pinmemberdavojc14-Feb-08 3:02 
GeneralSetting the values of properties Pinmembersma29-Nov-06 23:24 
GeneralRe: Setting the values of properties Pinmembermgaerber18-Dec-06 0:10 
QuestionRe: Setting the values of properties [modified] PinmemberDigital Ric13-Jun-07 17:30 
GeneralRe: Setting the values of properties Pinmemberpsamwel3-Dec-07 18:36 
Questiondotnet 1.1 Pinmemberaibo8-Aug-06 1:30 
AnswerRe: dotnet 1.1 PinmemberStephen Erisman8-Aug-06 5:19 
QuestionRe: dotnet 1.1 Pinmemberaibo8-Aug-06 5:46 
QuestionNested objects PinmemberMikeonn11-Jul-06 3:38 
AnswerRe: Nested objects PinmemberStephen Erisman11-Jul-06 5:38 
QuestionFieldInfo not passed to Ldfld? PinmemberNathan Baulch6-Jul-06 19:33 
AnswerRe: FieldInfo not passed to Ldfld? PinmemberStephen Erisman7-Jul-06 6:43 
QuestionPurpose PinmemberTheSire4-Jul-06 0:33 
AnswerRe: Purpose PinmemberStephen Erisman4-Jul-06 13:44 
AnswerRe: Purpose PinmemberNordin Rahman23-Aug-08 20:06 
GeneralA better way... PinmemberJ. Dunlap23-Jun-06 20:13 
GeneralRe: A better way... PinmemberStephen Erisman24-Jun-06 6:30 
GeneralRe: A better way... PinmemberStevo Z7-Oct-10 11:50 
GeneralRe: A better way... PinprotectorMarc Clifton24-Jun-06 8:15 
GeneralRe: A better way... PinmemberJ. Dunlap24-Jun-06 10:13 
QuestionRe: A better way... PinmemberStephen Erisman24-Jun-06 14:34 
AnswerRe: A better way... PinmemberJ. Dunlap24-Jun-06 20:43 
AnswerRe: A better way... [modified] Pinmemberdave.dolan10-Sep-06 18:56 
QuestionRe: A better way... PinmemberKowDot7-Feb-07 7:09 
AnswerRe: A better way... PinmemberStephen Erisman16-Feb-07 12:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150414.5 | Last Updated 4 Jul 2006
Article Copyright 2006 by Stephen Erisman
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid