The meaning of life is to explore the world

IEnumerable and yield usage

Posted on By Jason Liu

Below is an example of using IEnumerable and yield.

static void Main(string[] args)
{
	Console.WriteLine("==== Multiple IEnumerable with values NOT changed:");
	foreach (var item in TestYield(3, false))
		Console.WriteLine(item.data);
	IEnumerable<C> iec;
	iec = TestYield(3, false);
	foreach (C item in iec) Console.WriteLine(item.data);
	iec = TestYield(3, false);
	foreach (C item in iec) Console.WriteLine(item.data);
	Console.WriteLine("==== Multiple IEnumerable with values changed:");
	iec = TestYield(3, true);
	foreach (var v in iec) Console.WriteLine(v.data);
	iec = TestYield(3, true);
	foreach (var v in iec) Console.WriteLine(v.data);
}

public class C
{
	public C(int dataIn) { data = dataIn; }
	public int data;
}

public static IEnumerable<C> TestYield(int count, bool addRandom)
{
	int initValue = addRandom ? new Random().Next(10, 90) : 0;
	for( int i=0; i<count; i++ )
	{
		yield return new C(initValue + 2 * i);
		//initValue = -99;      // iteration resumes from the end of last yield, not the start of next yield
	}
}

Program result:
my_image