Adassko
Adassko

Reputation: 5343

Getting path from lambda expression

I have code like this:

string PropertyName<T>(Expression<Func<T>> expression)
{
    var body = expression.Body as MemberExpression;

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

    return body.Member.Name;
}

I use it in this fashion:

Console.WriteLine(PropertyName(() => this.Property));

which prints Property on screen

Now I would like to change it so:

Console.WriteLine(PropertyName(() => this.OtherObject.Property));

would give me OtherObject.Property instead of just Property. Is this even possible?

The purpose is to create bindings to dependency properties from code without hard coding of property names.

I also have a question when does the body on line 5 equals to null? I copied this code mindlessly and leave it at it was but this condition appears to never be true.

Upvotes: 1

Views: 728

Answers (1)

Aron
Aron

Reputation: 15772

    string PropertyName<T>(Expression<Func<T>> expression)
    {
        var body = expression.Body as MemberExpression;

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

        return string.Join(".", GetPropertyNames(body).Reverse());
    }

    private IEnumerable<string> GetPropertyNames(MemberExpression body)
    {
        while (body != null)
        {
            yield return body.Member.Name;
            var inner = body.Expression;
            switch (inner.NodeType)
            {
                case ExpressionType.MemberAccess:
                    body = inner as MemberExpression;
                    break;
                default:
                    body = null;
                    break;

            }
        }
    }

Upvotes: 4

Related Questions