Given:
FieldInfo field = <some valid string field on type T>;
ParameterExpression targetExp = Expression.Parameter(typeof(T), "target");
ParameterExpression valueExp = Expression.Parameter(typeof(string), "value");
How do I compile a lambda expression to set the field on the "target" parameter to "value"?
.Net 4.0 : now that there's
Expression.Assign
, this is easy to do:.Net 3.5 : you can't, you'll have to use System.Reflection.Emit instead:
Actually there is a way to set properties and fields with Expression Trees in .NET 3.5. It is may be the only option for some PCL profiles that do not support
Delegate.CreateDelegate
(besides the Reflection.Emit):For field the trick is passing field as ref parameter,
e.g.
SetField(ref holder.Field, "NewValue");
The property (as already pointed by Marc) can be set by reflecting and calling its setter method.
The full proof of concept is provided below as NUnit test fixture.
I once made this class. Perhaps it helps:
test:
Setting a field is, as already discussed, problematic. You can can (in 3.5) a single method, such as a property-setter - but only indirectly. This gets much easier in 4.0, as discussed here. However, if you actually have properties (not fields), you can do a lot simply with
Delegate.CreateDelegate
:Just for completeness here is the getter: