Question

I am dropping this line after having visited different websites to try understand real time example of using custom enumeration. I got examples. But they lead me to confusion.

Example

Take 1

class NumberArray
{
    public int[] scores;

    public NumberArray()
    {
    }

    public NumberArray(int[] scores)
    {
        this.scores = scores;
    }

    public int[] Scores
    {
        get {return scores;}
    }

}

Take 2

public class Enumerator : IEnumerator
{
    int[] scores;
    int cur;
    public Enumerator(int[] scores)
    {
        this.scores = scores;
        cur = -1;
    }
    public Object Current
    {
        get {
            return scores[cur];
        }
    }

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

    public bool MoveNext()
    {
        cur++;
        if (cur < scores.Length)
            return true;
        else return false;
    }
}

public class Enumerable : IEnumerable
{
    int[] numbers;

    public void GetNumbersForEnumeration(int[] values)
    {
        numbers = values;
        for (int i = 0; i < values.Length; i++)
            numbers[i] = values[i];
    }

    public IEnumerator GetEnumerator()
    {
        return new Enumerator(numbers);
    }
}

Main

static void Main()
{
    int[] arr = new int[] { 1, 2, 3, 4, 5 };
    NumberArray num = new NumberArray(arr);
    foreach(int val in num.Scores)
    {
        Console.WriteLine(val);
    }

    Enumerable en = new Enumerable();
    en.GetNumbersForEnumeration(arr);

    foreach (int i in en)
    {
        Console.WriteLine(i);
    }
    Console.ReadKey(true);
}

In take 2, I followed the custom iteration to iterate the same integer array as I did in take 1. Why should I beat about the bush to iterate an integer by using custom iteration?

Probably I missed out the real-time custom iteration need. Can you explain me the task which I can't do with existing iteration facility? (I just finished my schooling, so give me a simple example, so that I can understand it properly).

Update : I took those examples from some site. There is nothing special in that code, we can achieve it very simply even without using custom iteration, my interest was to know the real scenario where custom iteration is quite handy.

Was it helpful?

Solution

Custom iterators are useful when the resources you are iterating are not pre-loaded in memory, but rather obtained as needed in each iteration. For example, in LINQ to SQL, when you do something like:

foreach(var employee in dataContext.Employees) {
    // Process employee
}

in each step of the foreach loop, the Employees table in the database is queried to get the next record. This way, if you exit the loop early, you haven't read the whole table, but only the records you needed.

See here for a real-world example: enumerate lines on a file. Here, each line is read from the file on each iteration of the foreach loop. (as a side note, .NET Framework 4 offers this same functionality built-in).

OTHER TIPS

To be honest, I am not entirely sure what you're asking, but if you're concerned about the difference between returning an array (as in take 1) and returning an iterator (take 2), here is my answer.

There a big difference between returning an array and returning an iterator. Returning an array means returning internal state (unless you make a copy as part of the return, but that is expensive). If you return an iterator, you just return an abstraction, that will let callers iterate state. This also means, that you can do lazy evaluation if you need to (something you obviously can't do if you're returning an array).

Also, with the support for iterators in C# 2, there is really no reason to implement IEnumerable by hand. Please see this question for additional detail Can someone demystify the yield keyword?

Just as another example where custom iteration has been useful to me in the past was to provide a common abstraction to recursively enumerate all nodes in a tree structure...

foreach (Node n in tree)
  //...do something
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top