2
Reply

NET interview questions: - What is the difference between IEnumerator and IEnumerable?

    Understanding IEnumerator and IEnumerable
    This will help you for sure

    IEnumerable is an interface that defines one method GetEnumerator which returns an IEnumeratorinterface,this in turn allows readonly access to a collection.

    An IEnumerable is a thing that can be enumerated.which simply means that it has a GetEnumerator method that returns an IEnumerator.

    An IEnumerator is a thing that can enumerate: it has the MoveNext, Current, and Reset methods.
    Below is snippet code for IEnumerable

    IEnumerableobjIenum = (IEnumerable)obj;
    foreach (stringstrinobjIenum)
    {
    MessageBox.Show(str);
    }
    In the above IEnumerablesnippet code you can read the data.
    Below is snipped code for IEnumerator.
    IEnumerableobjIenum = (IEnumerable)obj;
    foreach (stringstrinobjIenum)
    {
    IEnumeratorobjEnumerator= objIenum.GetEnumerator();
    while (objEnumerator.MoveNext())
    {
    string s = objEnumerator.Current.ToString();
    MessageBox.Show(s);
    }
    }

    In IEnumerator you can use MoveNext,Current, and Reset methods as I have used in above code.

    You will be also interested in watching the below video what are generics.


     

    Please click here to see more  .Net interview questions