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.",

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

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

    return propInfo;

Usage as follows ...

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

More info here

No comments:

Post a Comment

How to replace the watch battery in Logitech K750 solar power keyboard

Buy this battery Open the battery cover on the back of the keyboard, you’ll need...