Create lambda action from function expression

Posted by Martin Robins on Stack Overflow See other posts from Stack Overflow or by Martin Robins
Published on 2010-05-15T16:02:23Z Indexed on 2010/05/15 16:04 UTC
Read the original article Hit count: 214

Filed under:
|

It is relatively easy to create a lambda function that will return the value of a property from an object, even including deep properties...

Func<Category, string> getCategoryName = new Func<Category, string>(c => c.Name);

and this can be called as follows...

string categoryName = getCategoryName(this.category);

But, given only the resulting function above (or the expression originally used to create the function), can anybody provide an easy way to create the opposing action...

Action<Category, string> setCategoryName = new Action<Category, string>((c, s) => c.Name = s);

...that will enable the same property value to be set as follows?

setCategoryName(this.category, "");

Note that I am looking for a way to create the action programatically from the function or expression - I hope that I have shown that I already know how to create it manually.

I am open to answers that work in both .net 3.5 and 4.0.

Thanks.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about lambda-expressions