Complete these tasks to reinforce what you learned in this module.
Write an iterator that prints opening, yields first, second and third, and prints closing no matter how the consumer leaves. Main breaks after the second value.
yield returns inside a try, and the closing message in a finally.using System;
using System.Collections.Generic;
class Program
{
static IEnumerable<string> Lines()
{
// Announce opening, yield the three lines, and make sure
// the closing message runs even on an early break
yield break;
}
static void Main()
{
foreach (var line in Lines())
{
Console.WriteLine(line);
if (line == "second")
{
break;
}
}
}
}
This iterator should yield every item that parses as an int and skip the rest — but yield return inside a try with a catch does not compile. Rewrite it so it does.
int.TryParse(s, out value) does the job without a catch, and continue skips the items that fail.using System;
using System.Collections.Generic;
class Program
{
static IEnumerable<int> Parsed(string[] items)
{
foreach (var s in items)
{
// Yield s as an int when it parses, skip it when it does not.
// A try/catch around the yield will not compile — find another way.
}
yield break;
}
static void Main()
{
foreach (var n in Parsed(new string[] { "1", "x", "3" }))
{
Console.WriteLine(n);
}
}
}