Pattern: Iterator
Iterator design pattern allows to traverse a container and access the container's elements.
Purpose of .NET implementation
Any collection should be able to loop through its elements.
So the iterator pattern could be retrieved almost anywhere in Array, IEnumerable , Hashset, List, and more.
Example in .NET :
DirectoryEnumerable
DirectoryEnumerable example for Pattern Iterator
namespace Iterator;
internal class DirectoryEnumerableDemo
{
public static void DirectoryEnumerableFiles(int nrMaxFiles)
{
var count = 0;
//what if we called Directory.GetFiles
foreach (var file in Directory.EnumerateFiles(@"c:\","*.*",SearchOption.AllDirectories))
{
count++;
if (count > nrMaxFiles)
break;
Console.WriteLine(file);
}
}
}
See Source Code for Microsoft implementation of Iterator
SourceCode Directory.GetFilesSourceCode IEnumerable
SourceCode IEnumerator
Learn More
C2Wikidofactory
DPH
Wikipedia
Homework
With the Yield keyword implement a function that return an IEnumerable of generic int that will return the first 10 numbers of the Fibonacci sequence.