3

This is mot likely a duplicate, but I couldn't find a proper question.

I want to get "MyClass.Name" from () => MyClass.Name. How do I define the method parameter and how do I convert the expression to a string?

jgauffin
  • 99,844
  • 45
  • 235
  • 372

2 Answers2

6

That is an Expression<Func<string>>, so you could have:

void Foo(Expression<Func<string>> selector) {...}

or

void Foo<T>(Expression<Func<T>> selector) {...}

however, note that the syntax MyClass.Name refers to a static property; if you want an instance property you might need something more like an Expression<Func<MyClass,string>> - for example:

static void Foo<TSource, TValue>(
    Expression<Func<TSource, TValue>> selector)
{

}
static void Main() {
     Foo((MyClass obj) => obj.Name);        
}

As for implementation; in this simple case, we can expect the Body to be a MemberExpression, so:

static void Foo<TSource, TValue>(
    Expression<Func<TSource, TValue>> selector)
{
    var member = ((MemberExpression)selector.Body).Member;
    Console.WriteLine(member.ReflectedType.Name + "." + member.Name);
}

However, it is more complex in the general case. This will also work if we use the static member:

static void Foo<TValue>(
    Expression<Func<TValue>> selector)
{
    var member = ((MemberExpression)selector.Body).Member;
    Console.WriteLine(member.ReflectedType.Name + "." + member.Name);
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

It depends on whether Name is static property.
1.If it is not static then MyClass.Name will not be a valid syntax at all. So let's assume that in this case you want to get class+property from local variable usage like this:

var instance = new MyClass();
string result = GetClassAndPropertyName(() => instance.Name);

So the implementation for GetClassAndPropertyName should be like this:

public static string GetClassAndPropertyName<T>(Expression<Func<T>> e)
{
    MemberExpression memberExpression = (MemberExpression) e.Body;
    return memberExpression.Member.DeclaringType.Name + "." + memberExpression.Member.Name;
}

Another syntax you can find in Marc's answer.

2.Name property could also be static, which is unlikely on my opinion, but it will allow following syntax, which is exact syntax as you have asked for:

string result = GetClassAndPropertyName(() => MyClass.Name);
Snowbear
  • 16,924
  • 3
  • 43
  • 67