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"