Reputation: 36656
does the .net compiler knows to produce a tail recursion fromt the followin code?
(meaning it knows that no backtracking should be made, because of the &&
?)
public bool DeleteLocation(Guid locationId)
{
return ((_mLocationDal.Save(locationRes) != null) &&
locationRes.ChildrenIds.Aggregate(true,
(succeededSoFar, next) => succeededSoFar &&
DeleteLocation(next)));
}
Upvotes: 1
Views: 120
Reputation: 726479
Even if C# compiler supported tail recursion optimization (which it does not) it wouldn't detect it in case of your program, because DeleteLocation
does not call itself directly. A functor that it uses calls DeleteLocation
, but that is not enough to optimize a recursive tail call.
On a side note, All
provides a more compact replacement for Aggregate
in your case:
public bool DeleteLocation(Guid locationId) {
return (_mLocationDal.Save(locationRes) != null) &&
locationRes.ChildrenIds.All(next => DeleteLocation(next));
}
Upvotes: 2
Reputation: 48230
The C# compiler doesn't support the tail recursion at all, if by "tail" you mean calling methods with the CIL's .tail
prefix which does not leave a frame on the stack.
Upvotes: 1
Reputation: 60190
The C# compiler doesn't emit tail calls at all AFAIK. The JIT of the CLR may discover and apply tail calls however.
Upvotes: 5
Reputation: 20600
Boolean expressions are evaluated lazily; e.g. in A && B
, B
is never evaluated if A
is false. This is why it's safe to do things like if (thing != null && thing.DoSomething())
.
Upvotes: 1