Iterators and Nullable Types
(Page 1 of 4 )
In this sixth part of a ten-part series that covers C# in depth, we will wrap up our discussion of iterators and begin looking at nullable types. It is excerpted from chapter four of
C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.
Composing Sequences
Iterators are highly composable. We can extend our example, this time to output even Fibonacci numbers only:
using System;
using System.Collections.Generic;
class Test
{
static void Main()
{
foreach (int fib in EvenNumbersOnly(Fibs(6)))
Console.WriteLine(fib);
}
static IEnumerable<int>Fibs(int fibCount)
{
for (int i = 0, prevFib = 1, curFib = 1; i < fibCount; i++)
{
yield return prevFib;
int newFib = prevFib+curFib;
prevFib = curFib;
curFib = newFib;
}
}
static IEnumerable<int>EvenNumbersOnly(IEnumerable<int>sequence)
{
foreach(int x in sequence)
if ((x % 2) == 0)
yield return x;
}
}
Each element is not calculated until the last moment—when requested by aMoveNext() operation. Figure 4-1 shows the data requests and data output over time.

Figure 4-1. Composing sequences
The composability of the iterator pattern is extremely useful in LINQ; we will discuss the subject again in Chapter 8.
Constructing an Enumerable Object
You can instantiate and populate an enumerable object in a single step. For example:
using System.Collections.Generic;
...
List<int>list = new List<int>{1, 2, 3};
The compiler translates this to the following:
using System.Collections.Generic;
...
List<int>list = new List<int>();
list.Add (1);
list.Add (2);
list.Add (3);
This requires that the enumerable object implements theSystem.Collections.IEnumerableinterface, and that it has anAddmethod that takes a single argument.
Next: Nullable Types >>
More C# Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Check it out today at your favorite bookstore. Buy this book now.
|
|