Skip to content

Instantly share code, notes, and snippets.

@xanathar
Created September 11, 2014 14:34
Show Gist options
  • Save xanathar/51f5a699645cfa6d120a to your computer and use it in GitHub Desktop.
Save xanathar/51f5a699645cfa6d120a to your computer and use it in GitHub Desktop.
Get/Set instance property using expression trees dynamic code
// This builds untyped accessors. Remove converts for strong typing.
var paramExp = Expression.Parameter(typeof(object), "obj");
var castParamExp = Expression.Convert(paramExp, this.UserDataDescriptor.Type);
var propAccess = Expression.Property(castParamExp, PropertyInfo.Name);
var castPropAccess = Expression.Convert(propAccess, typeof(object));
var lambda = Expression.Lambda<Func<object, object>>(castPropAccess, paramExp);
Func<object, object> getter = lambda.Compile();
MethodInfo setterMethod = PropertyInfo.GetSetMethod();
var paramExp = Expression.Parameter(typeof(object), "obj");
var paramValExp = Expression.Parameter(typeof(object), "val");
var castParamExp = Expression.Convert(paramExp, this.UserDataDescriptor.Type);
var castParamValExp = Expression.Convert(paramValExp, this.PropertyInfo.PropertyType);
var callExpression = Expression.Call(castParamExp, setterMethod, castParamValExp);
var lambda = Expression.Lambda<Action<object, object>>(callExpression, paramExp, paramValExp);
Action<object, object> setter = lambda.Compile();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment