Hi Guys
NP88 yield keyword
http://www.java2s.com/Tutorial/CSharp/0220__Data-Structure/Asimpleexampleofaniterator.htm
I got this program from the above website. What is the function of yield keyword? Anyone knows please explain.
Thank you
using System;
using System.Collections;
class MyClass
{
char[] chrs = { 'A', 'B', 'C', 'D' };
public IEnumerator GetEnumerator()
{
foreach (char ch in chrs)
yield return ch;
}
}
class MainClass
{
public static void
{
MyClass mc = new MyClass();
foreach (char ch in mc)
Console.Write(ch + " ");
Console.WriteLine();
}
}
/*
A B C D
*/
Posted Mar 18, 2008, 10:46 AM
Thank you for your explanation, Alan.
AlanPosted Mar 18, 2008, 10:42 AM
The 'yield' keyword is only found in 'iterator blocks' which are used to generate an ordered sequence of values in a collection class. There are two forms:
'yield return' returns the next element in the iteration.
'yield break' indicates that the iteration is complete.
The sequence of values is typically consumed by a foreach statement which is iterating through the collection in question.
An iterator block can only be used to implement a method, property or operator which returns an IEnumerator, IEnumerable or the generic equivalents of these interfaces. So the GetEnumerator() method, which all IEnumerable collections must contain, is a suitable candidate for an iterator. An iterator is not allowed to contain an ordinary 'return' statement.
It is intended as a convenience for the programmer and the compiler automatically generates the (often complex) code needed to implement the iterator.