Correctly checking arguments
suggest changeAn iterator method is not executed until the return value is enumerated. It’s therefore advantageous to assert preconditions outside of the iterator.
public static IEnumerable<int> Count(int start, int count)
{
// The exception is thrown when the method is called, not when the result is iterated
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
return CountCore(start, count);
}
private static IEnumerable<int> CountCore(int start, int count)
{
// If the exception was thrown here it would be raised during the first MoveNext()
// call on the IEnumerator, potentially at a point in the code far away from where
// an incorrect value was passed.
for (int i = 0; i < count; i++)
{
yield return start + i;
}
}
Calling Side Code (Usage):
// Get the count
var count = Count(1, 4);
// Iterate the results
foreach(var x in count)
{
Console.WriteLine(x);
}
Output:
1 2 3 4
When a method uses yield to generate an enumerable the compiler creates a state machine that when iterated over will run code up to a yield. It then returns the yielded item, and saves its state.
This means you will not find out about invalid arguments (passing null, for example) when you first call the method, because that only creates the state machine. You find out when the first element is requested, because only then does the method body run. A normal method that checks the arguments first reports the failure at the call. This is failing fast.
When using C# 7+, the CountCore function can be conveniently hidden into the Count function as a local function. See example here.