0

Is it possible to write a function that return the string value of a property of an object?

if I have an object called apple that has a method called peel i would like to have a method that returns "peel" when I call getAttributeName(apple.peel).

How can I do it?

MaPi
  • 1,601
  • 3
  • 31
  • 64

1 Answers1

5

You can write an extension method

public static string GetPropName<T, P>(this T obj, Expression<Func<T, P>> lambda)
{
    var member = lambda.Body as MemberExpression;
    var prop = member.Member as PropertyInfo;
    return prop.Name;
}

and use it like this

var u = new User();
string name = u.GetPropName(x=>x.name);
L.B
  • 114,136
  • 19
  • 178
  • 224