Get string names of properties and fields

/// <summary>
/// Helper class to assist in getting the string names of properties and fields from a given class.
/// </summary>
public static class PropertyNameHelper
{
    /// <summary>
    /// Gets the name of the property represented by the expression for the given type.
    /// </summary>
    /// <typeparam name="T">The type of object being queried.</typeparam>
    /// <param name="expression">The expression.</param>
    /// <returns>Returns the string name of the property/member represented in the expression.</returns>
    public static string GetPropertyName<T>(this T dataObject, Expression<Func<T, object>> expression)
    {
        return PropertyNameHelper.GetPropertyName<T>(expression);
    }

    /// <summary>
    /// Gets the name of the property represented by the expression for the given type.
    /// </summary>
    /// <typeparam name="T">The type of object being queried.</typeparam>
    /// <param name="expression">The expression.</param>
    /// <returns>Returns the string name of the property/member represented in the expression.</returns>
    public static string GetPropertyName<T>(Expression<Func<T, object>> expression)
    {
        // Get the body part of the passed-in expression.
        Expression expression_body = expression.Body;
        if (expression_body == null)
        {
            throw new ArgumentException(string.Format("Expression '{0}' refers to a method, not a property.",
                expression.ToString()));
        }

        // Check if the body represents an expression accessing a class member.
        if (expression_body is MemberExpression)
        {
            // The expression represents a class member, so return the name
            // of the member that the expression represents.
            return (expression_body as MemberExpression).Member.Name;
        }

        // Check if the body represents a unary expression.
        if (expression_body is UnaryExpression)
        {
            // Get the operand of the unary expression, which should be
            // a member expression.
            MemberExpression operand = (expression_body as UnaryExpression).Operand as MemberExpression;
            if (operand == null)
            {
                // No operand was found, so return an empty string.
                return String.Empty;
            }

            // The operand contains the name of the member in the expression.
            return operand.Member.Name;
        }

        // Nothing found, so return an empty string.
        return String.Empty;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>