Extracting property name at compile time

2012, Mar 28    
Just an extract from this article. It’s something I always find VERY useful (in situations where speed is not one of our concerns, of course)
protected string ExtractPropertyName<T>(Expression<Func<T>> propertyExpression) {
    if (propertyExpression == null) {
        throw new ArgumentNullException("propertyExpression");
    }
 
    var memberExpression = propertyExpression.Body as MemberExpression;
    if (memberExpression == null) {
        throw new ArgumentException("The expression is not a member access expression.", "propertyExpression");
    }
 
    var property = memberExpression.Member as PropertyInfo;
    if (property == null) {
        throw new ArgumentException("The member access expression does not access a property.", "propertyExpression");
    }
 
    if (!property.DeclaringType.IsAssignableFrom(this.GetType())) {
        throw new ArgumentException("The referenced property belongs to a different type.", "propertyExpression");
    }
 
    var getMethod = property.GetGetMethod(true);
    if (getMethod == null) {
        // this shouldn't happen - the expression would reject the property before reaching this far
        throw new ArgumentException("The referenced property does not have a get method.", "propertyExpression");
    }
 
    if (getMethod.IsStatic) {
        throw new ArgumentException("The referenced property is a static property.", "propertyExpression");
    }
 
    return memberExpression.Member.Name;
}    

Did you like this post? Then