Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C#
Article

IEnumerable And IEnumerator interfaces

Rate me:
Please Sign up or sign in to vote.
3.92/5 (37 votes)
17 Jul 2008CPOL3 min read 255K   3.3K   56   34
Using IEnumerable And IEnumerator interfaces in C#

Background

I have been seeing quite a number of posts in various discussion boards regarding ‘how to implement iterative access in a custom collection?’. Personally, for newbies, it was an alien step to appreciate the implementation of iterative access for their custom collection even though we have literatures and proven examples. This was the notion of writing an article on IEnumerable, IEnumerator interfaces, which facilitates the iterative access in a custom collection along with a well articulated graph and code sample.

Introduction

Unlike C++, .NET Framework facilitates accessing individual elements in the custom collection while implementing IEnumerable and IEnumerator interfaces. For example, it is a hassle free job to access types collected in an ArrayList. This had been eased by ArrayList class while implementing IEnumerable and IEnumerator interfaces.

Before continuing, let me explain the structure, members of the IEnumerable, IEnumerator interfaces. The IEnumerable interface contains an abstract member function called GetEnumerator() and return an interface IEnumerator on any success call. This IEnumerator interface will allow us to iterate through any custom collection.

Note: IEnumerator interface is meant to be used as accessors and is not helpful to make any changes in the collection or elements of the collection.

Presumably, any element in a collection can be retrieved through its index property. But instead of element index, the IEnumerator provides two abstract methods and a property to pull a particular element in a collection. And they are Reset(), MoveNext() and Current.

See the figure. This is how it works.

Image 1

IEnumerator GetEnumerator()

The signature of GetEnumerator() is as follows:

C#
public IEnumerator GetEnumerator()
{
            //return IEnumerator of our Custom Type
            return(IEnumerator)this;
}

Members of IEnumerator Interface

Reset(), MoveNext(), Current()

The signature of IEnumerator members is as follows:

  • void Reset()
  • bool MoveNext()
  • object Current

Refer to the figure which depicts three object instances in the custom collection.

The void Reset() method returns a void type and helps you to position the pointer just before the start point. Refer to the figure where I have three instances and the pointer is in the empty position. This reset method will also help you to reset the iteration pointer anywhere from the start position. For example, you are in the second instance and need to start from first. In addition to all, the reset method has to be called after any successive addition, deletion of elements in the collection.

C#
public void Reset()
{
   //Get total number of element in a collection
   length=slist.Count;

   //Setting the pointer to just before the beginning of collection
   current=-1;
}

The bool MoveNext() method will help you to position the location of the required element in the collection while sending a flag value. And its objective is to inform the caller whether the current position holds any value or not. If it has, then MoveNext will return true or return false in case there is no value. In addition, the MoveNext will help you to position the first element in the collection after calling the reset method.

C#
public bool MoveNext()
{
//this will increment the counter variable 
//and will check whether it is exceeding the actual length of our collection
return(++current<length);
}

The object Current property of IEnumerator interface will return an individual element of a given collection. This property is used to return an element in the collection by using the specified location pointer.

I.e. If you want to iterate through the collection, you need to call the MoveNext() method just before the Current. Otherwise, it will return the same element that the current property previously returns as output. In addition, if you are trying to enumerate for the first time, then you need to call methods and properties in this hierarchy: Reset() - > MoveNext () -> Current.

C#
public object Current
{
          get
          {
          //Here "slist" is the collection and "current" is the location pointer
          return(slist[current]);
          }
}

Personally, I feel the code which is available along with the article is explanatory enough to give a clear picture for further tunings.

C#
static  void Main()
{
          //Now this instance will contain a collection of MyClass Types
          Iterator It=new Iterator();
          //Am trying to access like normal array
          foreach(MyClass MY in It)
          {
                   Console.WriteLine("Name : "+MY.Name.ToString());
                   Console.WriteLine("Age : "+MY.Age.ToString());
          }
}

The aforementioned code is a part in my first example and tries to access the individual elements without implementing the required interfaces. But this code will fail to compile and the message is:

foreach statement cannot operate on variables of type 'CustomCollection.Iterator' 
because 'CustomCollection.Iterator' does not contain a definition 
for 'GetEnumerator', or it is inaccessible

I address the above compilation error in the second example while implementing IEnumearble, IEnumerator interfaces.

C#
//Definition for IEnumerator.Reset() method.
public void Reset()
{
          Cnt=-1;
}
//Definition for IEnumerator.MoveNext() method.
public bool MoveNext()
{
     return (++ Cnt < ClassArray.Length);
}
//Definition for IEnumerator.Current Property.
public object Current
{
     get
    {
          return ClassArray[Cnt];
    }
}
//Definition for IEnumerable.GetEnumerator() method.
public IEnumerator GetEnumerator()
{
       return (IEnumerator)this;
}

See the downloads at the top of this article for the source code.

History

  • 9th September, 2004: Initial post
  • 17th July, 2008: Article updated

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Freelance
India India
He is a certified professional in both MCPD and MCTS. He is a mathematics graduate with masters in computer science.He was born and bred in India and happen to spend some time in Europe.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Shweta_10124713-Apr-12 19:41
Shweta_10124713-Apr-12 19:41 
GeneralMy vote of 5 Pin
lokesh0319-Dec-11 1:18
lokesh0319-Dec-11 1:18 
QuestionGood one.. Pin
K.Kirivarnan19-Jul-11 18:21
K.Kirivarnan19-Jul-11 18:21 
GeneralUnsafe Pin
Luc Pattyn17-Jul-08 14:44
sitebuilderLuc Pattyn17-Jul-08 14:44 
GeneralWill be more good if you have provided much more comparison Pin
N a v a n e e t h1-Oct-07 23:50
N a v a n e e t h1-Oct-07 23:50 
Generalbeginner level Pin
DynV21-Jun-07 10:58
DynV21-Jun-07 10:58 
GeneralRe: beginner level Pin
sreejith ss nair21-Jun-07 17:27
sreejith ss nair21-Jun-07 17:27 
GeneralRe: beginner level Pin
DynV21-Jun-07 17:40
DynV21-Jun-07 17:40 
GeneralRe: beginner level Pin
inyd25-Nov-07 17:10
inyd25-Nov-07 17:10 
QuestionIenumerable Pin
ARTRAL15-Nov-06 0:44
ARTRAL15-Nov-06 0:44 
QuestionError running Example 2 ? Pin
newfon8-Jan-06 15:15
newfon8-Jan-06 15:15 
AnswerRe: Error running Example 2 ? Pin
sreejith ss nair7-Aug-06 4:52
sreejith ss nair7-Aug-06 4:52 
GeneralRe: Error running Example 2 ? Pin
Afshin Ketabchi21-Oct-06 5:51
Afshin Ketabchi21-Oct-06 5:51 
GeneralGreat example, and downloadable Source #2 needs to be updated for .Net Framework 2.0 Pin
Frank Th. van de Ven30-Nov-05 1:15
Frank Th. van de Ven30-Nov-05 1:15 
GeneralRe: Great example, and downloadable Source #2 needs to be updated for .Net Framework 2.0 Pin
sreejith ss nair30-Nov-05 1:19
sreejith ss nair30-Nov-05 1:19 
General[Message Deleted] Pin
Allen Anderson22-Sep-05 14:47
Allen Anderson22-Sep-05 14:47 
GeneralRe: good article Pin
sreejith ss nair22-Sep-05 17:32
sreejith ss nair22-Sep-05 17:32 
GeneralGreat Example even for Newbies Pin
andyj1212318-May-05 1:21
andyj1212318-May-05 1:21 
GeneralGood one sreejit Pin
VsPillai19-Sep-04 22:02
VsPillai19-Sep-04 22:02 
GeneralRe: Good one sreejit Pin
sreejith ss nair19-Sep-04 22:26
sreejith ss nair19-Sep-04 22:26 
Wink | ;) . thanks

**************************
S r e e j i t h N a i r
**************************
GeneralMore explanation Pin
Steven Campbell9-Sep-04 18:43
Steven Campbell9-Sep-04 18:43 
GeneralRe: More explanation Pin
sreejith ss nair9-Sep-04 21:33
sreejith ss nair9-Sep-04 21:33 
GeneralRe: More explanation Pin
sreejith ss nair10-Sep-04 0:48
sreejith ss nair10-Sep-04 0:48 
GeneralRe: More explanation Pin
Colin Angus Mackay10-Sep-04 1:38
Colin Angus Mackay10-Sep-04 1:38 
GeneralRe: More explanation Pin
sreejith ss nair10-Sep-04 1:44
sreejith ss nair10-Sep-04 1:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.