Search code examples
c#linqexpression-trees

How to check if an expression is empty (void)?


What is the best way to check if a System.Linq.Expressions.Expression instance is empty? For example, something like this:

Expression expression = Expression.Empty();
...
if (expression.IsEmpty) { ...

only that IsEmpty does not exist.

One idea is to test the outcome of ToString:

if (expression.ToString() == "default(Void)") { ...

but that doesn't seem right.


Solution

  • According to the documentation Empty() returns

    A DefaultExpression that has the NodeType property equal to Default and the Type property set to Void.

    so you should be able to use:

    if(expression.NodeType == ExpressionType.Default && expression.Type == typeof(void))