UPDATE: There is a nice post which explains how to and provides code for accessing methods or properties with refactor safe code. http://www.codeducky.org/10-utilities-c-developers-should-know-part-two/
All the given answers will work. However, none are refactor safe. I thought I'd offer a solution that a bit more refactor safe.
//Create a dictionary of columnName => property info using the GetPropertyInfo method.
public static IDictionary<string, PropertyInfo> propertyInfos = new Dictionary<string, PropertyInfo>
{
{"Name", GetPropertyInfo((Customer c) => c.Name) }
};
List<Customer> Customers= new List<Customer> { new Customer { Name = "Peter Pan" } };
Customer customer = Customers[0];
string column = "Name";
PropertyInfo propertyInfo = propertyInfos[column];
//Set property
propertyInfo.SetValue(customer, "Captain Hook", null);
//Get property -- Returns Captain Hook
object propertyValue = propertyInfo.GetValue(customer, null);
I've taken GetPropertyInfo
from this answer. I slightly modified it by removing the source
parameter because you can see by HappyNomad's comment that it's not necessary for the newest version of C#.
public static PropertyInfo GetPropertyInfo<TSource, TProperty>(Expression<Func<TSource, TProperty>> propertyLambda)
{
Type type = typeof(TSource);
MemberExpression member = propertyLambda.Body as MemberExpression;
if (member == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
propertyLambda.ToString()));
PropertyInfo propInfo = member.Member as PropertyInfo;
if (propInfo == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
propertyLambda.ToString()));
if (type != propInfo.ReflectedType &&
!type.IsSubclassOf(propInfo.ReflectedType))
throw new ArgumentException(string.Format(
"Expresion '{0}' refers to a property that is not from type {1}.",
propertyLambda.ToString(),
type));
return propInfo;
}
My suggestion is a bit more refactor safe because you'll hit a compile time error every time you change the Name
property on Customer
.
Side note: I agree with Tim S.. You'll likely be able to find a safer and more performant way than reflection :).