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?

4
  • 2
    First hit on google: csharp-examples.net/reflection-property-names Commented Feb 24, 2014 at 15:24
  • Why are you trying to do this? Commented Feb 24, 2014 at 15:25
  • 1
    If you know the method is called "peel", you can just put "peel" in a string. Hard to see what's your point here. Commented Feb 24, 2014 at 15:25
  • 1
    I don't believe you couldn't see one of questions like Get name of property as a string when you typed title of your question Commented Feb 24, 2014 at 15:28

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.