c# – Get string name of property using reflection

c# – Get string name of property using reflection

If you already have a PropertyInfo, then @dtbs answer is the right one. If, however, youre wanting to find out which propertys code youre currently in, youll have to traverse the current call stack to find out which method youre 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, Im wondering if what youre 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, youd write something like this:

var propertyName = GetPropertyName(
    () => myObject.AProperty); // returns AProperty

With C# 6.0 (Visual Studio 2015), you can now use the nameof operator, like this:

var obj = new MyObject();
string propertyName = nameof(obj.Property);
string methodName = nameof(obj.Method);
string directPropertyName = nameof(MyObject.Property);
string directMethodName = nameof(MyObject.Method);

c# – Get string name of property using reflection

PropertyInfo.Name

Leave a Reply

Your email address will not be published. Required fields are marked *