Create lambda action from function expression
- by Martin Robins
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.