Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

Hydrating Objects With Expression Trees - Part II

5.00/5 (1 vote)
16 Aug 2010CPOL 12.7K  
If the intent is to hydrate the objects from data, why not have an expression that does just that?

free hit counters

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 have 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:

C#
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] = Expression.Bind(
        property,
        Expression.Convert(
            Expression.ArrayAccess(
                valuesArrayExpression,
                Expression.Constant(p, typeof(int))
            ),
            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:

C#
for (int o = 0; o < objects.Length; o++)
{
    newObjects[o] = compiledObjectHidrationBLOCKED EXPRESSION;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)