
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Implementing Iterators as Overloaded Operators
|
349
This code produces the following output:
Display all data in both sets
item1
item11
item2
item2
item3
XYZ
item30
item11
item11
item2
item12
item1
Display only unique data in both sets
item1
item11
item2
item3
XYZ
item30
item12
Display only duplicate data in both sets
item1
item11
item2
Discussion
In addition to allowing methods and property get accessors to be iterator methods,
operator overloads can also be made into iterator methods. To become an iterator
method, the operator overload method simply has to return a
System.Collections.
IEnumerable
or a System.Collections.Generic.IEnumerable<T> type and implement
the
yield return statement.
The
+ operator is overloaded to yield every element of each Set object, both the lhs
and rhs Set objects. From the foreach loop’s perspective, this effectively allows the
loop to iterate over every
Set object that is added together as if it were one big Set
object. The foreach loop is able to make use of this overloaded operator since the
return value of this method is an
IEnumerable<T> type. Therefore, a simple foreach
loop can be set up as follows to return all elements of two Set objects:
foreach (string s in (set1 + set2))
The | operator is overloaded to return only unique items from both Set objects in the
expression. It