Complete these tasks to reinforce what you learned in this module.
Walk a List<int> without using foreach. Call GetEnumerator(), then loop with MoveNext() and print each Current on its own line.
var e = numbers.GetEnumerator(); while (e.MoveNext()) { ... e.Current ... }using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var numbers = new List<int> { 3, 1, 4 };
// Walk the list without foreach: GetEnumerator, MoveNext, Current
}
}
MoveNext is the only thing missing. Make Countdown(3) produce 3, 2, 1 and then stop. Remember that an enumerator starts *before* the first element.
using System;
using System.Collections;
using System.Collections.Generic;
class Countdown : IEnumerable<int>
{
private readonly int _from;
public Countdown(int from) => _from = from;
public IEnumerator<int> GetEnumerator() => new CountdownEnumerator(_from);
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
private class CountdownEnumerator : IEnumerator<int>
{
private int _current;
public CountdownEnumerator(int from) => _current = from + 1;
public int Current => _current;
object IEnumerator.Current => Current;
public bool MoveNext()
{
// Step down one, and say whether we still have a value
return false;
}
public void Reset() { }
public void Dispose() { }
}
}
class Program
{
static void Main()
{
foreach (var n in new Countdown(3))
{
Console.WriteLine(n);
}
}
}