The Fibonnaci Sequence using C# Iterators
Iterators in C# are probably one of the least understood and most wonderful features the language has. They were added in C# 2.0 and are the magic that gives LINQ its Deferred Execution goodness. Anyway, I was needing an arbitrary length list of Guids today (although, with the recent shortage, perhaps ScottGuIDs would have been a better choice) and used this cute little few-liner to get what I wanted:
public IEnumerable<Guid> Guids
{
get
{
while (true)
{
yield return Guid.NewGuid();
}
}
}
From there you can easily get yourself a list of, say, 5 Guids using LINQ’s Take Extension Method:
var myGuids = this.Guids.Take(5);
Obviously, this made me want to generate some more interesting sequences, like Fibonnaci’s:
public IEnumerable<int> Fibonnaci
{
get
{
int first = 0;
yield return first;
int second = 1;
yield return second;
while (true)
{
int next = first + second;
first = second;
second = next;
yield return next;
}
}
}
Pretty terse, right?