Skip to content

Instantly share code, notes, and snippets.

@zHaytam
Created November 17, 2020 20:43
Show Gist options
  • Save zHaytam/d6a7c7fa1c8157feed76536324e5f6db to your computer and use it in GitHub Desktop.
Save zHaytam/d6a7c7fa1c8157feed76536324e5f6db to your computer and use it in GitHub Desktop.
private static Func<object, object> GenerateGetterLambda(PropertyInfo property)
{
// Define our instance parameter, which will be the input of the Func
var objParameterExpr = Expression.Parameter(typeof(object), "instance");
// 1. Cast the instance to the correct type
var instanceExpr = Expression.TypeAs(objParameterExpr, property.DeclaringType);
// 2. Call the getter and retrieve the value of the property
var propertyExpr = Expression.Property(instanceExpr, property);
// 3. Convert the property's value to object
var propertyObjExpr = Expression.Convert(propertyExpr, typeof(object));
// Create a lambda expression of the latest call & compile it
return Expression.Lambda<Func<object, object>>(propertyObjExpr, objParameterExpr).Compile();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment