Jan 6, 2010

Using lambda expression to remove string expression

public class Customer
{
    public string Name { get; set; }
}

[TestMethod]
public void can_get_value_from_lamda_expression()
{
    Customer c = new Customer() { Name = "fred" };
    //
    Expression<Func<Customer, object>> propertyExpression = cust => cust.Name;
    Assert.AreEqual("Name", GetPropertyName(propertyExpression));
    Assert.AreEqual("fred", GetPropertyValue(c, propertyExpression));
    //
    Assert.AreEqual("Name", GetPropertyName<Customer>(cust => cust.Name));
    Assert.AreEqual("fred", GetPropertyValue(c, cust => cust.Name));
}

private string GetPropertyName<T>(Expression<Func<T, object>> propertyExpression)
{
    return (propertyExpression.Body as MemberExpression).Member.Name;
}

private object GetPropertyValue<T>(T target, Expression<Func<T, object>> propertyExpression)
{
    Func<T, object> getValue = propertyExpression.Compile();
    return getValue(target);
}