Search code examples
linqlinq-expressionscustom-linq-providers

What does System.Linq.Expressions.Expression.CanReduce property mean?


From the documentation, and its name implying, it can be inferred that the value of the CanReduce property must be set to true for all expressions that can further be decomposed into smaller expressions, and vice-versa.

But upon closer observation, this inference appears not to hold true in all cases. Take the case of LambdaExpression, which certainly is a composite unit. But the LambdaExpression class, deriving directly from the Expression class, does not override the CanReduce property. The Expression class defines the CanReduce property as virtual with an implementation that returns false, thus implying that a lambda expression is not further reducible, which is not true.

What then is the real meaning of this property?


Solution

  • I think you're reading the documentation wrong. "Reducing" here doesn't mean decomposing into multiple simpler expressions, it means transforming into a single expression that uses more basic operations. For example, consider the following ListInitExpression (using C#-like syntax):

    new List<int> { 1, new Random().Next() }
    

    Calling CanReduce on this expression will return true. And calling Reduce() will return:

    {
        Param_0 = new List<int>();
        Param_0.Add(1);
        Param_0.Add(new Random().Next());
        return Param_0;
    }
    

    It's not clear to me what should Reduce() on a LambdaExpression return, so it makes sense to me that it's not reducible.