C# – IEnumerator and IEnumerable

Categories: Programming
Tags:
Comments: No Comments
Published on: July 31, 2010

IEnumerator and IEnumerable are interfaces that are used to enumerate through a collection.
IEnumerator has a non generic correspondence IEnumerator which has MoveNext() method that returns a boolean, Current read only property that returns the current item in the collection. Reset, which resets the pointer (Enumerator) to -1. IEnumerator pointers begin with -1, and upon moving to the next element, pointer becomes 0, which we usually start processing. Classes that implments IEnumerable interface should implement GetEnumerator, IEnumerable.GetEnumerator methods which exposes the Enumerator to the caller.

Moreover, classes that implements IEnumerable and IEnumerator should implements all the methods and properties that belong to IEnumerator and IEnumerable, and also Dispose method.

class MyEnumerator : IEnumerator, IEnumerable
{
private List list;
private int pointer = -1;

public MyEnumerator()
{
list = new List();
}

public T this[int i]
{
set
{
list.Add(value);
}

get
{
return list[i];
}
}

public T Current
{
get
{
return list[pointer];
}
}

object IEnumerator.Current
{
get
{
return list[pointer];
}
}

public bool MoveNext()
{
if (++pointer < list.Count)
{
return true;
}
else
{
return false;
}
}

public void Reset()
{

}

public void Dispose()
{

}

public IEnumerator GetEnumerator()
{
return this;
}

IEnumerator IEnumerable.GetEnumerator()
{
return this;
}

}

Share this

Welcome , today is Tuesday, February 7, 2012

Bad Behavior has blocked 251 access attempts in the last 7 days.