If I have a class Product:
public class Product
{
public string Title { get; set; }
public string Make { get; set; }
public Decimal Price { get; set; } //(Edit) - Added non-string
}
And I have a property in another class declared as:
Func<Product, object> SortBy { get; set; }
I can set SortBy using:
SortBy = p => p.Title;
But how would I, using reflection, make the same assignment if I had the property name for SortBy stored as a string e.g.
string sortField = "Title";
SortBy = /*Some reflection using sortField*/;
To make it work with decimal and other value types, you can use generics:
...
The answer is effectively the same as this other SO question/answer on INotifyPropertyChanged by Phil.
You need to use expression trees to create a new method at runtime:
To work with value types, you'll need to insert a cast: