Complete these tasks to reinforce what you learned in this module.
Write the iterator so the program prints its lines in the order shown: the iterator's own message must appear only once the foreach begins.
Console.WriteLine("iterator started"); as the first statement of the iterator, before the first yield return.using System;
using System.Collections.Generic;
class Program
{
static IEnumerable<int> Numbers()
{
// Announce that the body has started, then hand back 1 and 2
yield break;
}
static void Main()
{
Console.WriteLine("before call");
var seq = Numbers();
Console.WriteLine("after call");
foreach (var n in seq)
{
Console.WriteLine(n);
}
}
}
Split FirstN so that passing null throws at the moment of the call, before anyone enumerates. Main is already written to detect which it is.
throw in a method with no yield in it, and have that method return a second, private iterator method.using System;
using System.Collections.Generic;
class Program
{
static IEnumerable<int> FirstN(int[] source, int count)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
for (int i = 0; i < count && i < source.Length; i++)
{
yield return source[i];
}
}
static void Main()
{
IEnumerable<int> seq;
try
{
seq = FirstN(null, 3);
}
catch (ArgumentNullException)
{
Console.WriteLine("threw on call");
return;
}
try
{
foreach (var n in seq) { }
}
catch (ArgumentNullException)
{
Console.WriteLine("threw on enumerate");
}
}
}
Write an iterator over { "1", "2", "boom", "4" } that yields each item parsed as an int. Main prints values until the parse fails. Show that the first two values arrive before the failure does.
int.Parse throws on "boom". Just yield int.Parse(item) for every item and let it happen.using System;
using System.Collections.Generic;
class Program
{
static IEnumerable<int> Parsed(string[] items)
{
// Yield every item parsed as an int
yield break;
}
static void Main()
{
var items = new string[] { "1", "2", "boom", "4" };
try
{
foreach (var n in Parsed(items))
{
Console.WriteLine(n);
}
}
catch (FormatException)
{
Console.WriteLine("caught");
}
}
}