Thursday, 1 March 2012

Accessing properties in C# using Lambda Expression Trees

The following code example shows how to reference properties on classes using Lambda expressions, rather than having to rely on a myType.GetType().GetProperties().First(prop => prop.Name == "MyPropertyName") type search, which would not be as easy to refactor in the future.

Here's a method that'll return the PropertyInfo object for the expression. It throws an exception if the expression is not a property.

public PropertyInfo GetPropertyInfo<TSource, TProperty>(
    TSource source,
    Expression<Func<TSource, TProperty>> propertyLambda)
{
    Type type = typeof(TSource);

    MemberExpression member = propertyLambda.Body as MemberExpression;
    if (member == null)
        throw new ArgumentException(string.Format(
            "Expression '{0}' refers to a method, not a property.",
            propertyLambda.ToString()));

    PropertyInfo propInfo = member.Member as PropertyInfo;
    if (propInfo == null)
        throw new ArgumentException(string.Format(
            "Expression '{0}' refers to a field, not a property.",
            propertyLambda.ToString()));

    if (type != propInfo.ReflectedType &&
        !type.IsSubclassOf(propInfo.ReflectedType))
        throw new ArgumentException(string.Format(
            "Expresion '{0}' refers to a property that is not from type {1}.",
            propertyLambda.ToString(),
            type));

    return propInfo;
}

Usage as follows ...

var propertyInfo = GetPropertyInfo(someUserObject, u => u.UserID);
 

More info here


http://stackoverflow.com/questions/671968/retrieving-property-name-from-lambda-expression

No comments:

Post a Comment

Android mediaserver process killing battery life

If this happens to you, then do the following Force stop on Settings, Applications, All, Media Storage. Clear Cache and Clear Data, fo...