This page does not contain anything you can’t find better explained elsewhere.  However, these methods show up in a lot of my code so I figure I had better post them.

Methods to get the Property Name referenced in a Lambda Expression

The below methods act on lambda expressions of the form “x => x.SomeProperty” and return the name of the referenced property (“SomeProperty” in this case).

The first method is for the typical case where one doesn’t know at compile time what the return type of the property is.  Therefore it is implemented using a return type of object.  The second method is for the occasional situation where the return type is known and one wants to use a strongly typed lambda.

For a fuller explanation of these methods see this excellent blog post from which I shamelessly lifted it.

For an example of how to use these methods, see this post.

using System;
using System.Linq.Expressions;
using System.Reflection;
 
static class ExpressionExtensionMethods
{
    public static string GetReferencedPropertyName
        (this Expression propertyReference)
    {
        return GetPropertyNameReferencedByExpression(propertyReference);
    }
 
    public static string GetReferencedPropertyName
        (this Expression propertyReference)
    {
        return GetPropertyNameReferencedByExpression(propertyReference);
    }
 
    private static string GetPropertyNameReferencedByExpression
        (LambdaExpression propertyReference)
    {
        MemberExpression memberExpression;
        var unary = propertyReference.Body as UnaryExpression;
        if (unary != null)
            //In this case the return type of the property was not object,
            //so .Net wrapped the expression inside of a unary Convert()
            //expression that casts it to type object. In this case, the
            //Operand of the Convert expression has the original expression.
            memberExpression = unary.Operand as MemberExpression;
        else
            //when the property is of type object the body itself is the
            //correct expression
            memberExpression = propertyReference.Body as MemberExpression;
 
        if (memberExpression == null
            || !(memberExpression.Member is PropertyInfo))
            throw new ArgumentException(
                "Expression was not of the form 'x => x.property'.");
 
        return memberExpression.Member.Name;
    }
}