
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
350
|
Chapter 6: Iterators and Partial Types
of it. Once this is completed, all of the tempSet object elements are yielded. Finally,
the
rhs Set object is examined for any elements that are not already contained within
the
tempSet object. All of the unique values from the rhs are also yielded.
The
& operator is overloaded to return only the items from the lhs Set object that are
duplicated in the
rhs Set object. It does this by first creating a temporary Set object
(
tempSet), which contains all values of the lhs Set object after the duplicate values
have been stripped out of it. Once this is completed, the
rhs Set object is examined
for any duplicate elements that are contained within the
tempSet Set object. If a
duplicate is found, that element is yielded.
This code works fine if we are constructing
foreach loops that contain only one of
these operators in the expression. For example, this works fine:
foreach (string s in (set1 + set2))
However, the following code will cause problems:
foreach (string s in (set1 + set2 + set3))
The reason for this is that the expression is evaluated as ((set1 + set2) + set3).
Therefore the result of the inner equation is an
IEnumerable<T>, which is then added
to
set3. In order for this equation to work, we also need to overload the + operator to
accept a
Set<T> object ...