So I've been playing with dynamically building expression trees lately and came across this method, which seems kinda odd. At first I thought "oh cool this is exactly what I need" after constantly writing code along the lines of
var left = member is FieldInfo ? Expression.Field(instance, (FieldInfo)member) : Expression.Property(instance, (PropertyInfo)member);
var right = ...
var assign = Expression.Assign(left, right);
Yes, I know there is Expression.PropertyOrField()
call, but it does roundtrip back to reflection to find member by name, where as I typically already have MemberInfo
instance.
So anyway, I thought Expression.Bind()
would be useful to me, but it does something I don't really understand. Given the following code:
void Main()
{
var m = typeof(Foo).GetField("Bar");
Expression.Bind(m, Expression.Constant("")).Dump();
}
public class Foo
{
public string Bar;
}
it produces MemberAssignment
expression Bar = ""
. But there is no instance and no static reference. How would I ever apply this expression to and instance of Foo
? I can't find any example of this method being used.
Expression.New()
to accept that. It didn't occur to me that could be a totally different call. – Cinerama