I have a method for evaluating expression:
static T GetFromDynamicExpression<T>(string expression, object entity) where T : class
{
ParameterExpression itParameter = Expression.Parameter(entity.GetType());
LambdaExpression lambdaExpression = DynamicExpression.ParseLambda(new[] { itParameter }, typeof(object), expression);
var classDelegate = lambdaExpression.Compile();
return classDelegate.DynamicInvoke(entity) as T;
}
I have two classes:
public class Student
{
public Address Address { get; set; }
}
public class Address
{
public string Name { get; set; }
}
I am using that method, for example:
var student = new Student() { };
string expression = "Address.Name";
var result = GetFromDynamicExpression<string>(expression, student);
In this case it is throwing exception:
NullReferenceException: Object reference not set to an instance of an object.
It is because Address of student is null. Now, I want my expression to check for null. It should return null (or default value of T) when Address is null. How can I do this?