I want to set private fields using LINQ expressions. I have this code:
//parameter "target", the object on which to set the field `field`
ParameterExpression targetExp = Expression.Parameter(typeof(object), "target");
//parameter "value" the value to be set in the `field` on "target"
ParameterExpression valueExp = Expression.Parameter(typeof(object), "value");
//cast the target from object to its correct type
Expression castTartgetExp = Expression.Convert(targetExp, type);
//cast the value to its correct type
Expression castValueExp = Expression.Convert(valueExp, field.FieldType);
//the field `field` on "target"
MemberExpression fieldExp = Expression.Field(castTartgetExp, field);
//assign the "value" to the `field`
BinaryExpression assignExp = Expression.Assign(fieldExp, castValueExp);
//compile the whole thing
var setter = Expression.Lambda<Action<object, object>> (assignExp, targetExp, valueExp).Compile();
This compiles a delegate that takes two objects, the target and the value:
setter(someObject, someValue);
The type
variable specifies the Type
of the target, and the field
variable is a FieldInfo
that specifies the field to be set.
This works great for reference types, but if the target is a struct, then this thing will pass the target as a copy to the setter delegate and set the value on the copy, instead of setting the value on the original target like I want. (At least that is what I think is going on.)
On the other hand,
field.SetValue(someObject, someValue);
works just fine, even for structs.
Is there anything I can do about this in order to set the field of the target using the compiled expression?
ref
, the only way would be assign the return value. – Rockhampton