Search code examples
c#stringlambdaexpression

How to build Expression tree in C# to check if string property is just null (no empty checking)


I found how to check if a property IsNullOrEmpty using:

var methodCall = Expression.Call(typeof(string), "IsNullOrEmpty", null, property);

But I need to check only if the property is null. Not check empty condition.

Can someone please advise me?
Thank you.

StackOverflows I passed through, but they are not my case and not helped:

The result should be an equiqalent to:

class A
{
  public string Text { get; set; }
}

A a = new A();

// this I need to construct with Expressions:  
bool isNull = a.Text == null;


Solution

  • You should be able to use Expression.Equal:

    var exp = Expression.Equal(theInstance, Expression.Constant(null, typeof(string)));
    

    Next create an VariableExpression and assign the previous value to it:

    exp = Expression.Assign(
        Expression.Variable(typeof(bool), "isNull"),
        exp);