C# provides a set of collections. These include Lists, LinkLists, Array, ArrayList, Dictionary and many more. We will discuss all the collection one-by-one in this series.
Enumeration
In C# there are many types of collections, from simple to complex. These collections differ from each other but traversing is a universal need. Traversing is supported by IEnumerable, IEnumerator, and their generic part IEnumerable<T>, IEnumerator<T>. IEnumerable, IEnumerator belongs to System.Collections namespace and IEnumerable<T>, IEnumerator<T>
belongs to System.Collections.Generic namespace.
IEnumerator
IEnumerator interface defines a basic low level protocol by which a collection is traversed in forward-only approach. If you see implementation in visual studio is looks like the following,
- public interface IEnumerator
- {
- object Current
- {
- get;
- }
- bool MoveNext();
- void Reset();
- }
Example 1:
- static void Main(string[] args)
- {
- int[] number = new int[]
- {
- 1,
- 2,
- 3,
- 4
- };
- IEnumerator enumerator = number.GetEnumerator();
- while (enumerator.MoveNext())
- {
- Console.WriteLine("Number is {0}", enumerator.Current);
- }
- }
Number is 1
Number is 2
Number is 3
Number is 4
Example 2:
- class Program
- {
- static void Main(string[] args)
- {
- string software = "SOFTWARE";
- IEnumerator enumerator = software.GetEnumerator();
- while (enumerator.MoveNext())
- {
- Console.WriteLine(enumerator.Current);
- }
- }
- }
sinraj vPosted Apr 13, 2016, 6:46 AM
Nice
Gowtham RajamanickamPosted Apr 12, 2016, 2:22 AM
nice
Humayun Kabir MamunPosted Apr 11, 2016, 3:48 AM
Nice...
Devinder YadavPosted Apr 8, 2016, 2:51 AM
Thanks Michael
Michael GriffithsPosted Apr 7, 2016, 10:58 AM
Nice explanation