views:

29

answers:

1

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.

+3  A: 

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.).

driis
Thank you! It was the *object* parameter to **Func** that had me stumped.
ProfK
No problem - Please remember to mark the answer as accepted if the answer solved your problem :-)
driis