I have an expression helper to help getting values from object hierarchy
public static Func<T, object> GetMemberExpressionFunc<T>(string expressionString)
{
if (string.IsNullOrEmpty(expressionString))
{
throw new InvalidOperationException("invalid Expression");
}
var parameter = Expression.Parameter(typeof(T));
Expression memberExpression = parameter;
var tokens = expressionString.Split('.');
memberExpression = tokens.Aggregate(memberExpression, Expression.PropertyOrField);
var convertExpression = Expression.Convert(memberExpression, typeof(object));
return Expression.Lambda<Func<T, object>>(convertExpression, parameter)
.Compile();
}
Usage
public class A
{
public B BObj { get; set; }
}
public class B
{
public string Name { get; set; }
}
static void Main(string[] args)
{
var obj = new A {BObj = new B {Name ="Test"}};
var obj2 = new A ();
var exp = ExpressionHelper.GetMemberExpressionFunc<A>("BObj.Name");
var test1 = exp(obj);// test1 is "Test"
var test2 = exp(obj2); //throws because BObj is null
}
I want the expression to return null if any property in the hierarchy is null instead of throwing exception. Is it possible to do this at the aggregate expression?