Created
January 27, 2020 10:25
-
-
Save mgravell/047f7fcfd2755819b8de7c5afaaf3001 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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