2

I am trying to make dynamic expression and assign lambda to it. As a result, I got exception: System.ArgumentException: Expression of type 'Test.ItsTrue' cannot be used for assignment to type 'System.Linq.Expressions.Expression`1[Test.ItsTrue]'

What is wrong?

public delegate bool ItsTrue();

public class Sample
{
    public Expression<ItsTrue> ItsTrue { get; set; }
}

[TestClass]
public class MyTest
{
    [TestMethod]
    public void TestPropertySetWithExpressionOfDelegate()
    {
        Expression<ItsTrue> itsTrue = () => true;

        // this works at compile time
        new Sample().ItsTrue = itsTrue;

        // this does not work ad runtime
        var new_ = Expression.New(typeof (Sample));

        var result = Expression.Assign(
            Expression.Property(new_, typeof (Sample).GetProperties()[0]), 
            itsTrue);
    }
}

1 Answer 1

1

The second argument of Expression.Assign is the expression representing the value to assign. So currently you're effectively trying to assign an ItsTrue to the property. You need to wrap it so that it's an expression returning the value itsTrue... either via Expression.Quote or Expression.Constant. For example:

var result = Expression.Assign(
    Expression.Property(new_, typeof (Sample).GetProperties()[0]), 
    Expression.Constant(itsTrue, typeof(Expression<ItsTrue>)));

Alternatively, you might want Expression.Quote - it really depends on what you're trying to achieve.

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

1 Comment

Thank you Jon, Expression.Quote is exactly what I expect to be there.

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.