Water Cooler v2
Water Cooler v2

Reputation: 33880

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?

Upvotes: 1

Views: 414

Answers (2)

Joe Friesenhan
Joe Friesenhan

Reputation: 442

I posted a longer answer here with more details: What does Expression.Reduce() do?, but the short form is that the out-of-box .NET behavior seems to only reduce the following scenarios:

  • Compound assignment e.g. x += 4
  • Pre/post increment/decrement e.g. x++, --y
  • Member and list initialization e.g. new List<int>() { 4, 5 }, new Thing() { Prop1 = 4, Prop2 = 5 }

Everything else is left as-is. I didn't see any evidence for or against dead expression culling as part of a reduce operation (e.g. an empty BlockExpression won't get removed from an expression tree during Reduce() calls).

Upvotes: 5

svick
svick

Reputation: 244928

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.

Upvotes: 1

Related Questions