Thursday, December 4, 2008

Yield Keyword in C#

One interesting new feature of the C# 2।0 is the "yield" keyword. Basically it is used to iterate through objects returned by a method. It creates a state engine in IL so you can create methods that retain their state and dont have to go through the pain of maintaining state in your code.



public static IEnumerable GetInt()
{
for (int i = 0; i <>
yield return i;
}


Here's the implementation.


class प्रोग्राम
{ static void Main(string[] args)
{
foreach (int i in GetInt())
Console।WriteLine("Got " + i।ToString());
}


public static IEnumerable GetInt()
{
for (int i = 0; i <>
yield return i;
}
}

Thanks,
Nitin Sharma