Skip to content

Instantly share code, notes, and snippets.

@makomweb
Created February 15, 2022 07:47
Show Gist options
  • Save makomweb/4fa171bb179eb7aad16844c9c33a112c to your computer and use it in GitHub Desktop.
Save makomweb/4fa171bb179eb7aad16844c9c33a112c to your computer and use it in GitHub Desktop.
Response to "Broken iterator example in C# from Entwickler Magazin 1 / 2022"
namespace Sandbox
{
public class MyTests
{
[Test]
public async Task Run_me()
{
var numbers = new List<int> { 1, 2, 3, 5, 8 };
var sum = SumAsync(numbers);
numbers.Add(13);
var result = await sum;
Assert.AreEqual(19, result);
}
#if false
/// <summary>
/// A naive implementation to sum numbers while faking business.
/// </summary>
/// <param name="numbers"></param>
/// <returns>The sum of the given numbers</returns>
private static async Task<int> SumAsync(IEnumerable<int> numbers)
{
var sum = 0;
#if false
// Option 1: Enumerate numbers by ignoring mutability
//
foreach (var n in numbers)
#else
// Option 2: Enumerate numbers by considering immutability!
//
foreach (var n in numbers.ToList())
#endif
{
await Task.Delay(100);
sum += n;
}
return sum;
}
#else
// Option 3:
//
/// <summary>
/// A more robust implementation to sum numbers using LINQ (without faking business).
/// </summary>
/// <param name="numbers"></param>
/// <returns>The sum of the given numbers.</returns>
private static Task<int> SumAsync(IEnumerable<int> numbers)
{
return Task.FromResult(
Enumerable.Sum(numbers)
);
}
#endif
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment