A C# paging iterator checks pageSize but throws ArgumentOutOfRangeException only when the caller first enumerates; why, and how does a local function make it throw at the call?
answer
- whole body waits for MoveNext
- split wrapper from body
- wrapper contains no yield
- same split for async methods
- thrown now vs stored in Task
basics
~20 sAny yield makes the whole method an iterator, so its checks run only on the first MoveNext. Keep the checks in a public method with no yield and return a local iterator function, so bad arguments throw at the call.
solid answer
~40 sA method containing `yield return` is compiled into an iterator: calling it only creates the sequence object, and none of its body, argument checks included, runs until the first `MoveNext`. So `Pages(items, 0)` returns happily and the `ArgumentOutOfRangeException` appears later, far from the bad call. The fix is to split the method: the public `Pages` has no `yield`, validates `source` and `pageSize`, then returns `Iterate(source, pageSize)`, a local iterator function holding the loop. The checks now run at the call, and the paging stays lazy. The same split works for `async` methods, whose exceptions are otherwise stored in the returned `Task`: a non-async wrapper validates and returns the local async function's task. A local function keeps the body private to its one caller, and it can be `static`, taking the validated values as parameters.
code
csharp · 34 linesusing System;
using System.Collections.Generic;
int[] items = [1, 2, 3, 4, 5];
var deferred = Paging.PagesDeferred(items, 0); // no exception here
Console.WriteLine("deferred: sequence returned");
try { foreach (var page in deferred) { } }
catch (ArgumentOutOfRangeException) { Console.WriteLine("deferred: threw on first MoveNext"); }
try { Paging.Pages(items, 0); }
catch (ArgumentOutOfRangeException) { Console.WriteLine("eager: threw at the call"); }
static class Paging
{
public static IEnumerable<int[]> PagesDeferred(int[] source, int pageSize)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pageSize);
for (int i = 0; i < source.Length; i += pageSize)
yield return source[i..Math.Min(i + pageSize, source.Length)];
}
public static IEnumerable<int[]> Pages(int[] source, int pageSize)
{
ArgumentNullException.ThrowIfNull(source);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pageSize);
return Iterate(source, pageSize);
static IEnumerable<int[]> Iterate(int[] source, int pageSize)
{
for (int i = 0; i < source.Length; i += pageSize)
yield return source[i..Math.Min(i + pageSize, source.Length)];
}
}
}go deeper
Recall that a method containing yield runs none of its body until enumeration starts, so its argument checks wait too.
Explain the split: a public method without yield validates and returns a local iterator function that holds the loop.
Apply the same split to async methods, know where each exception surfaces, and keep operational failures in the sequence or the Task.
Make eager argument validation a library convention for public iterator and async APIs, so misuse is reported at the faulty call site.
## The symptom A file-system scanner exposes a paging helper: ```csharp public static IEnumerable<int[]> PagesDeferred(int[] source, int pageSize) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pageSize); for (int i = 0; i < source.Length; i += pageSize) yield return source[i..Math.Min(i + pageSize, source.Length)]; } ``` `PagesDeferred(items, 0)` returns a sequence without complaint. The exception appears only when someone enumerates it, perhaps in another layer, long after the call that passed the bad value. The stack trace points at the enumeration, not at the caller who made the mistake. ## Why the check is deferred Any `yield return` or `yield break` in a method body makes the **whole method** an iterator. The compiler moves the body into a generated enumerator, and calling the method only creates that object. The first statement of the body, the guard included, runs on the first call to `MoveNext`. How the generated state machine works is covered with iterators; what matters here is that no part of an iterator body runs at the call. ## The wrapper-plus-local-iterator pattern 1. Keep the **public method free of `yield`**, so it is an ordinary method that runs at the call. 2. Put the **argument checks** first in it: `ArgumentNullException.ThrowIfNull(source)` and `ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pageSize)`. 3. **Return a local iterator function** that holds the loop and the `yield return` statements. ```csharp public static IEnumerable<int[]> Pages(int[] source, int pageSize) { ArgumentNullException.ThrowIfNull(source); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pageSize); return Iterate(source, pageSize); static IEnumerable<int[]> Iterate(int[] source, int pageSize) { for (int i = 0; i < source.Length; i += pageSize) yield return source[i..Math.Min(i + pageSize, source.Length)]; } } ``` Now `Pages(items, 0)` throws at the call, and `Pages(items, 2)` still produces pages lazily. ## The same split for async methods An `async` method has the mirror-image behaviour: an exception thrown before its first `await` does not reach the caller at the call, it is stored in the returned `Task`, which is already faulted when the call returns. A non-async wrapper changes that: | Method shape | Where a bad argument surfaces | |---|---| | iterator with checks inside | first `MoveNext`, when enumeration starts | | wrapper with no `yield` plus local iterator | at the call | | `async` method with checks inside | in the returned `Task`, seen when it is awaited | | non-async wrapper plus local `async` function | at the call, thrown synchronously | The wrapper returns `Task<int>` and is not marked `async`; it validates and then returns the local function's task. ## Capturing or static body The local body can capture the validated parameters, as the C# documentation's example does, or be marked `static` and take them as parameters (its parameters may shadow the outer names since C# 8). Both work. A capturing iterator or async local function puts its captures in a heap closure, but the iterator or the suspended async state needs an object anyway, so `static` is chosen mainly to make the data flow explicit. ## Pitfalls - A single `yield break` left in the wrapper turns it back into an iterator and defers the checks again. - Calling `ToList()` inside the method makes the checks eager but also **buffers** every page, which changes behaviour for large or infinite sources. - Validate **arguments** eagerly; failures of the work itself (an I/O error while paging, a cancelled operation) belong to enumeration time or to the `Task`. - For async methods, throwing at the call is a deliberate contract: callers that stored the task and awaited it later now see the exception earlier. Choose it for usage errors such as a null path. ## Checking the contract in a test A test for eager validation must **not enumerate** and must **not await**: it calls `Pages(items, 0)` and expects the exception from the call itself. A test that wraps the call in a `foreach` or awaits the task passes for both the broken and the fixed version, so it proves nothing about where the exception surfaces. Before C# 7 the same pattern needed a separate `private` method on the class. A local function keeps the body next to its single caller and makes it impossible to call the unvalidated body from anywhere else.
- Why can't the C# iterator's checks be made eager by putting them before a yield break at the top?Any `yield` statement anywhere in the method body makes the whole method an iterator. The compiler then moves every statement, including the checks and the `yield break`, into the generated enumerator, so nothing runs until the first `MoveNext`. Only a method with no `yield` at all executes at the call.
- Is throwing at the call always right for a C# async method's argument checks?It is right for usage errors such as a null or out-of-range argument, because the bug is in the caller and should surface there. Operational failures, such as an I/O error or cancellation, should stay in the returned `Task`, where callers that await it expect them. The wrapper makes that split explicit.
- Moving the checks to the first lines of the iterator makes them run at the call.
- An async method throws argument exceptions at the call if they come before the first await.
- Calling ToList inside the method is a free way to make the checks eager.
- The local iterator must capture the arguments; marking it static would break it.
- A yield break in the wrapper is harmless because it never executes.