0

I am trying to create an expression tree binding that will create an object if the property is available and place null if it is not. For example, I want to end up with:

personModel = car.Person == null ? null : new PersonModel() 

But no matter what I try it fails.

I tried coalesce

Expression.Coalesce( Expression.Property(param, "Person"), Expression.MemberInit(Expression.New(typeof(PersonModel)), MemberAssignment[]) ) 

This throws System.ArgumentException: 'Argument types do not match'. I assume the expression tree is expecting to place the same types in the coalesce - since I have a few nullable enumerates that work in the above scenario.

I tried conditional

Expression.Condition( Expression.Equal(Expression.Property(param, "Person"), Expression.Constant(null)), Expression.MemberInit(Expression.New(typeof(PersonModel)), MemberAssignment[]), Expression.Constant(null) ) 

This also throws System.ArgumentException: 'Argument types do not match' due to the true block having Expresison.MemberInit and the false block having Expression.Constant.

Is there anyway to make something like this work?

1 Answer 1

2

Your statement personModel = car.Person == null ? null : new PersonModel() can be translated as:

 Expression.Condition( Expression.Equal(Expression.Property(Expression.Constant(car), "Person"), Expression.Constant(null,typeof(PersonModel))), Expression.Constant(null, typeof(PersonModel)), Expression.MemberInit(Expression.New(typeof(PersonModel)))); 

Looks like what you missed to mention was the typeof for null constant as Expression.Constant(null,typeof(PersonModel)).

Explanation:

If you check the definition for .Condition it says it throws System.ArgumentException when

test.Type is not System.Boolean.-or-ifTrue.Type is not equal to ifFalse.Type

So, in your case , it is checking that the Type of values in both false and true expression is PersonModel. Compiler is able to conclude same for false (new PersonModel()) but not for true (null) so we need to explicitly state it.

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

2 Comments

Ah! Thanks @gkulshrestha! Any information on why we would need to specify the type of null?
@GrizzlyEnglish I added more details in my answer. Hope it helps.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.