Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null check for lambda expression tree

Tags:

c#

lambda

How can I check if property of String type is null in order my following code to work and not fail during method calling ?

if (SelectedOperator is StringOperators)
{
    MethodInfo method;

    var value = Expression.Constant(Value);

    switch ((StringOperators)SelectedOperator)
    {
        case StringOperators.Is:
            condition = Expression.Equal(property, value);
            break;

        case StringOperators.IsNot:
            condition = Expression.NotEqual(property, value);
            break;

        case StringOperators.StartsWith:
            method = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });
            condition = Expression.Call(property, method, value);
            break;

        case StringOperators.Contains:
            method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
            condition = Expression.Call(property, method, value);
            break;

        case StringOperators.EndsWith:
            method = typeof(string).GetMethod("EndsWith", new[] { typeof(string) });
            condition = Expression.Call(property, method, value);
            break;
    }
}
like image 769
GorillaApe Avatar asked Mar 09 '15 18:03

GorillaApe


1 Answers

Add a null check to the resultant expression using AndAlso, like this:

// Your switch stays as is
switch ((StringOperators)SelectedOperator) {
    case StringOperators.Is:
        condition = Expression.Equal(property, value);
        break;
    ...
}
// Create null checker property != null
var nullCheck = Expression.NotEqual(property, Expression.Constant(null, typeof(object)));
// Add null checker in front of the condition using &&
condition = Expression.AndAlso(nullCheck, condition);
like image 113
Sergey Kalinichenko Avatar answered Oct 20 '22 17:10

Sergey Kalinichenko