Search code examples
c#lambdaexpression-trees

How to use Expressions to check for !=null against user-defined data types?


I'm new to expressions. I'm trying this and it doesn't seem to work.

ParameterExpression pe = Expression.Parameter(typeof(Customer));
Expression left = Expression.Property(pe, "OrderList");
Expression right = Expression.Constant(null, typeof(Nullable));
Expression res = Expression.NotEqual(left, right);

I'm gettign an "InvalidOperationException". In simple If-Else statement is look like this

if(custObj.OrderList != null)
{...}

Any help would be great.


Solution

  • The problem is you are comparing objects of different types. You can solve this by using Expression.Constant(object value) overload, I'm assuming that the type of the property OrderList is by reference, if not you can't do this comparison.

    ParameterExpression pe = Expression.Parameter(typeof(Customer));
    Expression left = Expression.Property(pe, "OrderList");
    Expression right = Expression.Constant(null);
    Expression res = Expression.NotEqual(left, right);