blogs

miércoles, 24 de junio de 2015

IEnumerable interface

IEnumerable and IEnumerator interfaces:

Provide all methods that we need to can iterator in the elements of each collection or array.
1.Define a simple business object
2.Define a collection in term of simple business object. Every class must implement IEnumerable  such that we can use with a foreach.We must implement the GetEnumerator method.
3.When we implement IEnumerable, we also must implement IEnumerator interface.
 The enumerators must define them before the first element, index=-1
4.Use the define collection in term of simple business object.

using System.Collections;

Example:
if our business is about a library, and the book is very import for our business.
Simple business object: Library.
IEnumerable

Create a new class Book



Create a new class that implements the methods of IEnumerator


Create a new class that implements the method of IEnumerable

Create a test method in which we will fill  our array of books and where we will iterate our books collection.



 Our test run
Our library has a books collection

                            


Call to method getEnumerator


A our class that is implementing the methods IEnumerator


Verify that exist a next element to get the value because if the index is equals to length of  array can not get the data.


In this case the index=0 and length of array is equal to 6 so than shows the element






No hay comentarios:

Publicar un comentario