How to get name of current property

c#, system.reflection

Solution

If you truly mean the current property (question title):

public static string GetCallerName([CallerMemberName] string name = null) {
    return name;
}
...

public string Foo {
    get {
        ...
        var myName = GetCallerName(); // "Foo"
        ...
    }
    set { ... }
}

this pushes the work to the compiler rather than the runtime, and works regardless of inlining, obfuscation, etc. Note this needs a `using` directive of `using System.Runtime.CompilerServices;`, C# 5, and .NET 4.5 or similar.

If you mean the example:

var propName = new News().Name.Method;

then it isn't possible directly from that syntax; `.Name.Method()` would be invoking something (possibly an extension method) on the result of `.Name` - but that is just a.n.other object and knows nothing of where it came from (such as a `Name` property). Ideally to get `Name`, expression-trees are the simplest approach.

Expression<Func<object>> expr = () => new News().Bar;

var name = ((MemberExpression)expr.Body).Member.Name; // "Bar"

which could be encapsulated as:

public static string GetMemberName(LambdaExpression lambda)
{
    var member = lambda.Body as MemberExpression;
    if (member == null) throw new NotSupportedException(
          "The final part of the lambda is not a member-expression");
    return member.Member.Name;
}

i.e.

Expression<Func<object>> expr = () => new News().Bar;
var name = GetMemberName(expr); // "Bar"

Problem

I've got a class ``` public class News : Record { public News() { } public LocaleValues Name { get; set; } public LocaleValues Body; } ``` And in my `LocaleValues` class i have: ``` public class LocaleValues : List<LocalizedText> { public string Method { get { var res = System.Reflection.MethodBase.GetCurrentMethod().Name; return res; } } } ``` I need the `Method` property to return a string representation of `Name` property name when I make a call like this: ``` var propName = new News().Name.Method; ``` How can I achieve this? Thank you for your time!

Original source

Related problems