Convert a property getter to a setter

Convert a property getter to a setter

In the process of adding some strongly-typed extensions to the official MongoDB C# driver I needed some code to convert a property getter into a property setter. The following static method does that, turning e => e.Field into an Action method you can call to set the value of ‘Field’.

[csharp] /// \ /// Convert a lambda expression for a getter into a setter /// \ public static Action\ GetSetter\(Expression\<Func\> expression) { var memberExpression = (MemberExpression)expression.Body; var property = (PropertyInfo)memberExpression.Member; var setMethod = property.GetSetMethod();

var parameterT = Expression.Parameter(typeof(T), “x”); var parameterU = Expression.Parameter(typeof(U), “y”);

var newExpression = Expression.Lambda\<Action\>( Expression.Call(parameterT, setMethod, parameterU), parameterT, parameterU );

return newExpression.Compile(); } [/csharp]

Fri Sep 16 2011 04:52:40 GMT-0700 (Pacific Daylight Time)

Next page: Remember Everything ... a long-term project

Previous page: What if ... you could define and query an Ontology using natural language?