-4

Follow-up question based on What is the being called here: return _().

What is the point of declaring the local function below?

return _(); IEnumerable<TResult> _()
{
    var bucket = new TSource[collection.Count];
    collection.CopyTo(bucket, 0);
    yield return resultSelector(bucket);
}

Why not just replace the call with the function body?

var bucket = new TSource[collection.Count];
collection.CopyTo(bucket, 0);
yield return resultSelector(bucket);
Emanuel Vintilă
  • 1,911
  • 4
  • 25
  • 35
  • 2
    as per my earlier comment: compare and contrast here: https://gist.github.com/mgravell/047f7fcfd2755819b8de7c5afaaf3001 - not having the outer method be an iterator block allows a: eager parameter checking, and b: directly return (non-iterator-block) in the various other cases that it happens – Marc Gravell Jan 27 '20 at 16:36

1 Answers1

-2

The reason for declaring the local function is not apparent at first. Looking further, the encompassing method returns a IEnumerable<TResult>. There are two ways to return an IEnumerable from a method.

  1. Using the yield return statement with objects of type TResult
  2. Using the return statement with an object of type IEnumerable<TResult>

But, the two statements cannot be mixed throughout a single method, you will always have to use one or the other on all execution paths of a method.

By using a return statement earlier in the method, the same statement had to be used throughout the entire method.

Emanuel Vintilă
  • 1,911
  • 4
  • 25
  • 35
  • 1
    I don't find this explanation compelling. I can't think of a good reason why you would want to mix these two statements in the same method in the first place, and you haven't provided a code example illustrating the concept. – Robert Harvey Jan 27 '20 at 16:36
  • 2
    As Marc Gravell points out above, the reason is already adequately stated in the original post you linked. – Robert Harvey Jan 27 '20 at 16:37
  • @RobertHarvey A good reason would be: remove code bloat by inlining the local function declaration in the aforementioned code instead of, you know, declaring the local function right before calling it only once. – Emanuel Vintilă Jan 28 '20 at 18:22