I'm building a list of properties of a type to include in an export of a collection of that type. I'd like to do this without using strings for property names. Only certain properties of the type are to be included in the list. I'd like to do something like:
exportPropertyList<JobCard>.Add(jc => jc.CompletionDate, "Date of Completion");
How can I go about implementing this generic Add method? BTW, the string is the description of the property.
You can get the PropertyInfo object by examining the Expression passed in. Something like:
public void Add<T>(Expression<Func<T,object>> expression, string displayName)
{
var memberExpression = expression.Body as MemberExpression;
PropertyInfo prop = memberExpression.Member as PropertyInfo;
// Add property here to some collection, etc ?
}
This is an uncomplete implementation, because I don't know what exactly you want to do with the property - but it does show how to get the PropertyInfo from an Expression - the PropertyInfo object contains all meta data about the property. Also, be sure to add error handling to the above before applying it in production code (ie. guards against the expression not being a MemberExpression, etc.).
A superior selector configuration looks like this:
public void MethodConsumingSelector<TContainer, TSelected>(Expression<Func<TContainer, TSelected>> selector)
{
var memberExpresion = expression.Body as MemberExpression;
var propertyInfo = memberExpression.Member as PropertyInfo;
}
This prevents the expression being passed in from being a UnaryExpression containing Convert(x => x.ValueTypeProperty)
when your selector targets a value type.
See the related question regarding UnaryExpression versus MemberExpression on SO here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With