Question

I want to do this:

Console.WriteLine( PrintMyName(x => x.EmailAddress) );


public class User{
   public string EmailAddress{get;set;}
}

Now the problem is, as seen bellow that propertyInfo is null.

public string PrintMyName(Func<T,object> member){
   var propertyInfo = (member.Body as MemberExpression).Member as PropertyInfo;
   return propertyInfo.Name;
}

What is the righte way to do this? Thanks

Was it helpful?

Solution

should be something like this:

    public static string GetPropertyName<T>(Expression<Func<T, object>> expression)
    {
        var body = expression.Body as MemberExpression;

        if (body == null)
        {
            body = ((UnaryExpression)expression.Body).Operand as MemberExpression;
        }

        if (body != null)
        {
            return body.Member.Name;
        }

        return null;
    }

usage (use Tuple as an example):

var theName = GetPropertyName<Tuple<string>>(x => x.Item1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top