I want to take a class, loop through it’s properties, get the property value, and call a method passing that property value in. I think I can get the property values, but what does the lambda expression’s body look like? What body is used to call a method on each property?
This is what I have so far…
Action<T> CreateExpression<T>( T obj )
{
foreach( var property in typeof( T ).GetProperties() )
{
Expression value = Expression.Property( Expression.Constant( obj ), property );
var method = Expression.Call( typeof( SomeType ), "SomeMethod", null, value );
}
// What expression body can be used that will call
// all the method expressions for each property?
var body = Expression...
return Expression.Lambda<Action<T>>( body, ... ).Compile();
}
It depends on a few things.
does the method return anything?
Expressionin 3.5 can’t do multiple separate “action” operations (a statement body), but you can cheat if you can do something with a fluent API:(perhaps using generics to make it simpler)
do you have access to 4.0? In 4.0 there are additional
Expressiontypes allowing statement bodies and exactly what you ask for. I discuss some similar examples in an article here (look forExpression.Block, although this is based on a beta a while ago – it may have been renamed by now).Alternative; since you are compiling to a delegate, consider that an
Action<T>is multicast; you could build a set of simple operations, and combine them in the delegate; this would work in 3.5; for example: