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\ > 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\ >( 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: My first programme [sic]

Previous page: Dynamic persistence with MongoDB - look, no classes! Multiple inheritance in C#!


Disqus goes here