TheCatWhisperer
TheCatWhisperer

Reputation: 981

Get the property name of a property of an anonymous type from an expression

The following code works fine for regular types:

    public static string GetPropertyName(this Expression<Func<object>> property)
    {
        MemberExpression member = property.Body as MemberExpression;
        PropertyInfo propInfo = member.Member as PropertyInfo;
        return propInfo.Name;
    }

    GetPropertyName(() => obj.MyProperty); //Returns "MyProperty"

However, if you pass it the property from an anonymous type, it throws a null reference exception because the expression body is a UnaryExpression instead of a MemberExpression.

How can I make this function work properly for anonymous types?

Upvotes: 2

Views: 1753

Answers (1)

Douglas
Douglas

Reputation: 54877

The expression body is a UnaryExpression not because of the anonymous type, but because the property is a value type that needs to be boxed as an object for your Expression<Func<object>>; see this answer.

You can avoid this by changing your method signature to take a generic type parameter:

public static string GetPropertyName<T>(this Expression<Func<T>> property)

Upvotes: 7

Related Questions