03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

164 ❘ CHAPTER 7 Program Control Statements<br />

This code creates an enumerator to enumerate over Employee objects. It then enters a while loop.<br />

If enumerator.MoveNext returns true, the enumerator has successfully moved to the next object<br />

in the collection. As long as it has read an object, the program uses enumerator.Current to get the<br />

current object and displays that object’s Name property in the Console window.<br />

When it reaches the end of the employees list, the enumerator’s MoveNext method returns false<br />

and the loop ends.<br />

A foreach loop provides roughly the same access to the items in a container class as an enumerator.<br />

Under some circumstances, however, an enumerator may provide a more natural way to loop through<br />

a container class than a foreach loop. For example, an enumerator can skip several items without<br />

examining them closely. You can also use an enumerator’s Reset method to restart the enumeration.<br />

To restart a foreach loop, you would need to start the loop over.<br />

The IEnumerable interface defines the features needed for enumerators, so any class that implements<br />

the IEnumerable interface provides enumerators. Any class that supports foreach must also implement<br />

the IEnumerable interface, so any class that supports foreach also supports enumerators. A few<br />

of the classes that implement IEnumerable include the following:<br />

Array HybridDictionary SqlDataReader<br />

ArrayList ListDictionary Stack<br />

Collection MessageQueue String<br />

CollectionBase OdbcDataReader StringCollection<br />

ControlCollection OleDbDataReader StringDictionary<br />

DataView OracleDataReader TableCellCollection<br />

DictionaryBase Queue TableRowCollection<br />

DictionaryEntries ReadOnlyCollectionBase XmlNode<br />

Hashtable SortedList XmlNodeList<br />

Iterators<br />

An iterator is similar in concept to an enumerator. It also provides methods that enable you to step<br />

through the items in some sort of container object. Iterators are more specialized than enumerators<br />

and work with particular classes.<br />

For example, a GraphicsPath object represents a series of connected lines and curves.<br />

A GraphicsPathIterator object can step through the line and curve data contained in a<br />

GraphicsPath object.<br />

Iterators are much more specialized than enumerators. How you use them depends on what you<br />

need to do and on the kind of iterator, so they are not described in detail here.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!