0

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?

1 Answer 1

0

Looking at the GetFromDynamicExpression method it looks like you are assuming that the Entity being passed in will always be Student.

If that is the case, you could check the Entity (cast as a Student) and check if the Address is null.

Example:

static T GetFromDynamicExpression<T>(string expression, object entity) where T : class
        {
            ParameterExpression itParameter = Expression.Parameter(typeof(Student));

            LambdaExpression lambdaExpression = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { itParameter }, typeof(object), expression);

            var classDelegate = lambdaExpression.Compile();

            if(entity is Student)
            {
                var student = entity as Student;

                if(student.Address == null)
                {
                    return null;
                }
            }

            return classDelegate.DynamicInvoke(entity) as T;
        }

An alternative, and shorter way without worry about types would be to "new up" the Address property in the Student class:

public class Student
{
   public Address Address { get; set; } = new Address();
}

The result of this would also return null.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.