The IEnumerable Interface

You implement the IEnumerable interface each time you want your class to support For..Each loops. Each time you iterate an object (typically a collection) using For Each, it is because that object implements IEnumerable. The .NET Framework offers lots of collections (including generic ones) and enables creating custom collections inheriting from built-in ones; therefore, implementing IEnumerable will probably be spared for you. It’s important to understand how the interface works, especially for its intensive usage when working with LINQ. IEnumerable provides one method, named GetEnumerator, which generally is implemented as follows:

image

As you can see, the method returns the result of the conversion of the class instance to an IEnumerator object; this means that IEnumerable must be implemented together with another interface, named IEnumerator that offers methods and properties for moving between items in a collection and for providing information on the current item. To provide an example, imagine you have a class named Contacts that acts as a repository of items of type Contact and that implements IEnumerable to provide iterations’ capabilities. Listing 13.2 shows how this is accomplished in code, including a sample loop performed invoking For..Each.

Listing 13.2 Implementing IEnumerable and IEnumerator

image

image

image

The Contacts class stores an array of Contact objects and provides a private field, position, which is used for returning information. The Current property returns the item in the array corresponding to the current position, whereas the MoveNext method increments the position variable and returns True if the position number is still less than the upper bound in the array. In the end, Reset just restores the initial value for position. You also notice how, within the Sub Main in Module1, a simple For..Each loop is given for demonstration purposes. If you run the code, you see that it correctly returns last names for both actual contacts within the Contacts class.

IEnumerable(Of T)

As for other interfaces a generic version of IEnumerable supports specific types. Because Chapter 15, “Delegates and Events,” discusses generics, this chapter shows the nongeneric version that basically works the same except that it is related to Object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.67.185