views:

90

answers:

3

There is a whole wealth of reflection examples out there that allow you to get either:

    1. All properties in a class

    2. A single property, provided you know the string name

Is there a way (using reflection, TypeDescriptor, or otherwise) to get the string name of a property in a class at runtime, provided all I have is an instance of the class and property?

EDIT I know that I can easily get all the properties in a class using reflection and then get the name of each property. What I'm asking for is a function to give me name of a property, provided I pass it the instance of the property. In other words, how do I find the property I want from the PropertyInfo[] array returned to me from the class.GetType().GetProperty(myProperty) so that I can get the PropertyInfo.Name from it?

+2  A: 

PropertyInfo.Name

dtb
A: 

myClassInstance.GetType().GetProperties() gives you PropertyInfo instances for all public properties for myClassInstance's type. (See MSDN for documentation and other overloads.) ´PropertyInfo.Name´ is the actual name of the property. In case you already know the name of the property use GetProperty(name) to retrieve its PropertyInfo object (see MSDN again).

Ondrej Tucny
+6  A: 

If you already have a PropertyInfo, then @dtb's answer is the right one. If, however, you're wanting to find out which property's code you're currently in, you'll have to traverse the current call stack to find out which method you're currently executing and derive the property name from there.

var stackTrace = new StackTrace();
var frames = stackTrace.GetFrames();
var thisFrame = frames[0];
var method = thisFrame.GetMethod();
var methodName = method.Name; // Should be get_* or set_*
var propertyName = method.Name.Substring(4);

Edit:

After your clarification, I'm wondering if what you're wanting to do is get the name of a property from a property expression. If so, you might want to write a method like this:

public static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
    return (propertyExpression.Body as MemberExpression).Member.Name;
}

To use it, you'd write something like this:

var propertyName = GetPropertyName(
    () => myObject.AProperty); // returns "AProperty"
Jacob
@Jacob - Well done good sir, this is exactly what I was looking for. I'll add this to my helper function library. Thanks so much for keeping up with this question, even after the edit. ++cool.
Joel B
+1 for the use of Expression; I didn't understand the question this way.
Ondrej Tucny