Skip to content

Instantly share code, notes, and snippets.

@hoganlong
Created July 14, 2012 00:44
Show Gist options
  • Save hoganlong/3108507 to your computer and use it in GitHub Desktop.
Save hoganlong/3108507 to your computer and use it in GitHub Desktop.
MakeGetter code
class test
{
public string sam { get; set; }
public int anumber { get; set; }
}
void Main()
{
var z = new test { sam = "sam", anumber = 99};
var x1 = MakeGetter<test,int>("anumber");
var x2 = MakeGetter<test,string>("sam");
x1(z).Dump();
x2(z).Dump();
}
Func<T, RT> MakeGetter<T,RT>(string propertyName)
{
ParameterExpression input = Expression.Parameter(typeof(T));
var expr = Expression.Property(input, typeof(T).GetProperty(propertyName));
return Expression.Lambda<Func<T, RT>>(expr, input).Compile();
}
@hoganlong
Copy link
Author

Results

99
sam

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment