神刀安全网

Difference between IEnumerator and IEnumerable Interface in C#

In this article, we will discuss:

  • Enumerators and Enumerable types
  • How Enumerators work behind the scene?
  • IEnumerator Interface
  • IEnumerable Interface
  • Generic Enumeration Interfaces
  • Summary

Enumerators and Enumerable types

Definition :

The enumerator is an object that can return each item in a collection, one by one,in order, as they’re requested. The enumerator “knows” the order of the items and keeps track of where it is in the sequence. It then returns the current item when it is requested.An Enumerable is a type that has a method called GetEnumerator and that returns an enumerator, to retrieve its item.

let’s look at an example to understand Enumerators and Enumerables and how it works behind the scene.

In below example, We will declare an array with five elements, and then use a foreach loop to print out the values of the items.

class Program   {       static void Main()       {           int[] arr1 = { 1, 2, 3, 4, 5 }; // Define the array.             foreach (int itemin arr1) // Enumerate the elements.               Console.WriteLine("Item value: {0}", item);       }   } 

Output:

Item value: 1

Item value: 2

Item value: 3

Item value: 4

Item value: 5

Difference between IEnumerator and IEnumerable Interface in C#

so in the above example:

  • It gets the object’s enumerator by calling its GetEnumerator method.
  • It requests each item from the enumerator and makes it available to your code as the iteration variable, which your code can read

IEnumerator Interface :

An Enumerator implements IEnumerator Interface.It has two methods called MoveNext and Reset. It has a property called Current.

Difference between IEnumerator and IEnumerable Interface in C#

  • Current returns the item at the current position in the sequence.
    − It is a read-only property.
    − It returns a reference of type object, so an object of any type can be returned.
  • MoveNext is a method that advances the enumerator’s position to the next item inthe collection. It also returns a Boolean value, indicating whether the new position is a valid position or is beyond the end of the sequence.
    − If the new position is valid, the method returns true.
    − If the new position isn’t valid (that is, the current position is beyond the end),the method returns false.
    − The initial position of the enumerator is before the first item in the sequence,so MoveNext must be called before the first access of Current.
  • Reset is a method that resets the position to the initial state.

Example:

 class Program     {         static void Main()         {             List<int> list = new List<int>();             list.Add(1);             list.Add(2);             list.Add(3);             list.Add(4);             list.Add(5);               List<int>.Enumerator e = list.GetEnumerator();             Write(e);         }           static void Write(IEnumerator<int> e)         {             while (e.MoveNext())             {                 int value = e.Current;                 Console.WriteLine(value);             }         }     } 

Output:

1

2

3

4

5

IEnumerable Interface :

An enumerable class implements the IEnumerable interface. The IEnumerable interface has only one method : GetEnumerator, which returns an enumerator

Difference between IEnumerator and IEnumerable Interface in C#

Example:

usingSystem.Collections;   //Implement the IEnumerable interface class MyClass : IEnumerable { public IEnumerator GetEnumerator { ... } ...  } //Returns an object of type IEnumerator 

usingSystem.Collections; class MyColors: IEnumerable { string[] Colors = { "Red", "Yellow", "Blue" }; public IEnumeratorGetEnumerator() { return new ColorEnumerator(Colors);//An instance of the enumerator class }  } 

Example using IEnumerable & IEnumerator Interface:

 class ColorEnumerator : IEnumerator     {         string[] _colors;         int _position = -1;         public ColorEnumerator(string[] theColors) // Constructor         {             _colors = new string[theColors.Length];             for (int i = 0; i < theColors.Length; i++)                 _colors[i] = theColors[i];         }         public object Current // Implement Current.         {             get             {                 if (_position == -1)                     throw new InvalidOperationException();                 if (_position >= _colors.Length)                     throw new InvalidOperationException();                 return _colors[_position];             }         }         public bool MoveNext() // Implement MoveNext.         {             if (_position < _colors.Length - 1)             {                 _position++;                 return true;             }             else                 return false;         }         public void Reset() // Implement Reset.         {             _position = -1;         }     }     class Spectrum : IEnumerable     {         string[] Colors = { "violet", "blue", "cyan", "green", "yellow", "orange", "red" };         public IEnumeratorGetEnumerator()         {             return new ColorEnumerator(Colors);         }     }     class Program     {         static void Main()         {             Spectrumspectrum = new Spectrum();             foreach (string colorin spectrum)                 Console.WriteLine(color);         }     } 

Output:

violet blue cyan green yellow orange red 

Generic Enumeration Interfaces

We have discussed on Non Generic Enumeration Interfaces but in real time, we mostly use type safe, Generic Enumeration Interfaces. Those are IEnumerable and IEnumerator interfaces.

These are similar to IEnumerator and Ienumerable interfaces. The major differences between NonGeneric and Generic form are:

With the NonGeneric Interface form:

− The GetEnumerator method of interface IEnumerable returns an enumerator class instance that implements IEnumerator.− The class implementing IEnumerator implements property Current, which returns a reference of type object, which you must then cast to the actual type of the object.

With the Generic Interface form :

− The GetEnumerator method of interface IEnumerable returns an instance of a class that implements IEnumerator

.

− The class implementing IEnumerator implements property Current, which returns an instance of the actual type, rather than a reference to the base class object.

Summary:

In this article, We have discussed:

  • Enumerators and Enumerable types
  • How Enumerators work behind the scene?
  • IEnumerator Interface
  • IEnumerable Interface
  • Generic Enumeration Interfaces

You may also like: Difference Between IEnumerable, ICollection and IList Interface in C#

Thanks for visiting !!

© 2016,admin. All rights reserved.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Difference between IEnumerator and IEnumerable Interface in C#

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址