Tuesday, January 16, 2007

* CSharp Tip #4 : .NET Iterators

Iterators have been introduced in .NET 2.0. Iterator is used to enable support for foreach operation on a class or struct.

The iterator code uses the yield return statement to return each statement in turn. Multiple iterators can be implemented on a class. Each iterator must have a unique name and can be invoked by client code in a foreach statement as follows : foreach (int x in SampleClass.IteratorName)

Consider the following sample code which shows how to use iterators and how to have multiple iterators on same class.

 

using System;
using System.Collections.Generic;
using System.Text;

namespace VikasGoyal.Iterators
{
class Program
{
static void Main(string[] args)
{
SampleClass sc = new SampleClass();
Console.WriteLine("Version Numbers");
foreach (string i in sc.GetVersions())
{
Console.WriteLine(i);
}
Console.WriteLine("Version Names");
foreach (string i in sc.GetNames())
{
Console.WriteLine(i);
}
}
}

class SampleClass
{
string[] versions ={ "1.0", "2.0", "3.0" };
string[] names ={ "First", "Second", "Third" };

public System.Collections.IEnumerable GetVersions()
{
for (int i = 0; i < versions.Length; i++)
{
yield return versions[i];
}
}

public System.Collections.IEnumerable GetNames()
{
for (int i = 0; i < names.Length; i++)
{
yield return names[i];
}
}
}
}
OUTPUT
Version Numbers
1.0
2.0
3.0
Version Names
First
Second
Third



No comments:

Post a Comment