We have some code that given a property name uses reflection to implement a Comparer.
I would like to store a delegate/Func to get the value rather than paying the reflection price each time we need to get a value.
Given a class like this:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
I tried to write a function that would create a delegate for me
Func<T, object> CreateGetFuncFor<T>(string propertyName)
{
PropertyInfo prop = typeof(T).GetProperty(propertyName);
return (Func<T, object>)Delegate.CreateDelegate(typeof(Func<T, object>),
null,
prop.GetGetMethod());
}
The following code works fine for the getting the Name
var person = new Person { Name = "Dave", Age = 42 };
var funcitonToGetName = CreateGetFuncFor<Person>("Name");
Console.WriteLine(funcitonToGetName(person));
var functionToGetAge = CreateGetFuncFor<Person>("Age");
but for the Age proerty it throws an ArgumentException with the message "Error binding to target method"
What am I missing? Is there another way to do it?