Patterns and Iterators in C# - Iterator Semantics
(Page 4 of 4 )
An iterator is a method, property, or indexer that contains one or more yield statements. An iterator must return one of the following four interfaces (otherwise, the compiler will generate an error):
// Enumerable interfaces
System.Collections.IEnumerable
System.Collections.Generic.IEnumerable<T>
// Enumerator interfaces
System.Collections.IEnumerator
System.Collections.Generic.IEnumerator<T>
An iterator has different semantics, depending on whether it returns an enumerable interface or an enumerator interface. We describe this in Chapter 7.
Multiple yield statements are permitted. For example:
class Test
{
static void Main()
{
foreach (string s in Foo())
Console.WriteLine(s); // prints "One","Two","Three"
}
static IEnumerableFoo()
{
yield return "One";
yield return "Two";
yield return "Three";
}
}
Theyield breakstatement indicates that the iterator block should exit early, without returning more elements. We can modifyFooas follows to demonstrate:
static IEnumerable<string>Foo(bool breakEarly)
{
yield return "One";
yield return "Two";
if (breakEarly)
yield break;
yield return "Three";
}
Areturnstatement is illegal in an iterator block. Instead, ayield breakstatement is used to terminate the iteration.
Please check back next week for the continuation of this article.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
|
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.
|
|