1

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?

Douglas
  • 53,759
  • 13
  • 140
  • 188
TheCatWhisperer
  • 901
  • 2
  • 12
  • 28

1 Answers1

6

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)
Douglas
  • 53,759
  • 13
  • 140
  • 188