tags:

views:

63

answers:

1

I dont know anything about Ienumerable object.what is the role of Ienumarble interface in .net ? Please tell me whether it is in built? Is every class in .net automatically implements the Ienumarable interface ? why there is need to implement the ienumerable interface? what are the methods it contains & what roles they plays. Please explain in detail.

+1  A: 

In a nutshell, IEnumerable exposes an enumerator, which allows support of a simple iteration over a non-generic collection.

It basically allows foreach loops over a collection, i.e.:

foreach (Control control in this.Controls)
{
   // Do something
}

The only method you need implement to use IEnumable in your own class is GetEnumerator() which returns IEnumerator.

The IEnumerator you return must be a class that implements the following methods:

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

A basic example of an IEnumerator class, taken from here:

private class ClassEnumerator : IEnumerator
{
    private ClassList _classList;
    private int _index;

    public ClassEnumerator(ClassList classList)
    {
        _classList = classList;
        _index = -1;
    }

    #region IEnumerator Members

    public void Reset()
    {
        _index = -1;
    }

    public object Current
    {
        get
        {
            return _classList._students[_index];
        }
    }

    public bool MoveNext()
    {
        _index++;
        if (_index >= _classList._students.Count)
            return false;
        else
            return true;
    }

    #endregion
}
GenericTypeTea
**over a non-generic** collection.
Lukas Šalkauskas
@Lukas - woops.
GenericTypeTea
@Lukas Šalkauskas, please elaborate as the MSDN documentation simply states "collection" - not "non-generic collection".
Sohnee
@Sohnee - IEnumerable is for non-generic types. IEnumable<T> would be for generic types.
GenericTypeTea