Let\'s say I have the following code which update a field of a struct using reflection. Since the struct instance is copied into the DynamicUpdate
EDIT again: This works structs now.
There's a gorgeous way to do it in C# 4, but you'll have to write your own ILGenerator emit code for anything before that. They added an ExpressionType.Assign to the .NET Framework 4.
This works in C# 4 (tested):
public delegate void ByRefStructAction(ref SomeType instance, object value);
private static ByRefStructAction BuildSetter(FieldInfo field)
{
ParameterExpression instance = Expression.Parameter(typeof(SomeType).MakeByRefType(), "instance");
ParameterExpression value = Expression.Parameter(typeof(object), "value");
Expression expr =
Expression.Lambda(
Expression.Assign(
Expression.Field(instance, field),
Expression.Convert(value, field.FieldType)),
instance,
value);
return expr.Compile();
}
Edit: Here was my test code.
public struct SomeType
{
public int member;
}
[TestMethod]
public void TestIL()
{
FieldInfo field = typeof(SomeType).GetField("member");
var setter = BuildSetter(field);
SomeType instance = new SomeType();
int value = 12;
setter(ref instance, value);
Assert.AreEqual(value, instance.member);
}