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.
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).