hits counter

Hydrating Objects With Expression Trees - Part II

LINQ With C# (Portuguese)

In my previous post I showed how to hydrate objects by creating instances and setting properties in those instances.

But, if the intent is to hydrate the objects from data, why not having an expression that does just that? That’s what the member initialization expression is for.

To create such an expression we need the constructor expression and the property binding expressions:

var properties = objectType.GetProperties();
var bindings = new MemberBinding[properties.Length];
var valuesArrayExpression = Expression.Parameter(typeof(object[]), "v");

for (int p = 0; p < properties.Length; p++) { var property = properties[p];

bindings[p] = <span style="color: #2b91af">Expression</span>.Bind(
    property,
    <span style="color: #2b91af">Expression</span>.Convert(
        <span style="color: #2b91af">Expression</span>.ArrayAccess(
            valuesArrayExpression,
            <span style="color: #2b91af">Expression</span>.Constant(p, <span style="color: blue">typeof</span>(<span style="color: blue">int</span>))
        ),
        property.PropertyType
    )
);

}

var memberInitExpression = Expression.MemberInit( Expression.New(objectType), bindings );

var objectHidrationExpression = Expression.Lambda<Func<object[], object>>(memberInitExpression, valuesArrayExpression);

var compiledObjectHidrationExpression = objectHidrationExpression.Compile();

This might seem more complex than the previous solution, but using it is a lot more simple:

for (int o = 0; o < objects.Length; o++)
{
    newObjects[o] = compiledObjectHidrationExpression(objects[o]);
}

1 Comment

  • Hydrating Objects With Expression Trees - Part III
    To finalize this series on object hydration, I’ll show some performance comparisons between the different methods of hydrating objects.
    Code samples for this series of posts (and the one about object dumping with expression trees) can be found on my MSDN Code Gallery: Dump And Hydrate Objects With Expression Trees

Comments have been disabled for this content.