Romain Vergnory
Romain Vergnory

Reputation: 1598

Compare PropertyInfo name to an existing property in a safe way

I have a PropertyInfo, and I'd would like to check if it is a specific one. Knowing that its ReflectedType is correct, I could do this:

bool TestProperty(PropertyInfo prop)
{
    return prop.Name == "myPropertyName";
}

The problem is that my property myPropertyName could change name in the futur, and I would have no way to realize that the above code just broke.

Is there a safe way to test what I want, probably using Expression ?

Upvotes: 1

Views: 34

Answers (1)

Vadim Martynov
Vadim Martynov

Reputation: 8902

If you can make Expression for the property then it is possible to retrieve name from this expression:

public static string PropertyName<T>(this Expression<Func<T, object>> propertyExpression)
{
    MemberExpression mbody = propertyExpression.Body as MemberExpression;

    if (mbody == null)
    {
        //This will handle Nullable<T> properties.
        UnaryExpression ubody = propertyExpression.Body as UnaryExpression;

        if (ubody != null)
        {
            mbody = ubody.Operand as MemberExpression;
        }

        if (mbody == null)
        {
            throw new ArgumentException("Expression is not a MemberExpression", "propertyExpression");
        }
    }

    return mbody.Member.Name;
}

Then you can use it in next manner:

bool TestProperty(PropertyInfo prop)
{
    return prop.Name == Extensions.PropertyName<TargetClass>(x => x.myPropertyName);;
}

Upvotes: 1

Related Questions