Skip to content

Instantly share code, notes, and snippets.

@mgravell
Created January 27, 2020 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgravell/047f7fcfd2755819b8de7c5afaaf3001 to your computer and use it in GitHub Desktop.
Save mgravell/047f7fcfd2755819b8de7c5afaaf3001 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
string step = "n/a";
try
{
step = "initial call";
var sequence = Deferred(-1);
step = "foreach";
foreach (var item in sequence)
Console.WriteLine(item);
}
catch (Exception ex)
{
Console.WriteLine($"Deferred threw during {step}: {ex.Message}");
}
step = "n/a";
try
{
step = "initial call";
var sequence = Eager(-1);
step = "foreach";
foreach (var item in sequence)
Console.WriteLine(item);
}
catch (Exception ex)
{
Console.WriteLine($"Eager threw during {step}: {ex.Message}");
}
}
static IEnumerable<int> Deferred(int count)
{
if (count < 0) throw new ArgumentOutOfRangeException(nameof(count));
for (int i = 0; i < count; i++)
yield return i;
}
static IEnumerable<int> Eager(int count)
{
if (count < 0) throw new ArgumentOutOfRangeException(nameof(count));
return _();
IEnumerable<int> _()
{
for (int i = 0; i < count; i++)
yield return i;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment