Friday, April 11, 2008

Mainstream usage of yield (c#).

Let's review when csharp statement yield can be really useful. When we need process list (for example, display or calculate a parameter) of generated data we can use simple way and create array:

static public int[] PowerByArray(int number, int exponent)
{
int[] results = new int[exponent];
int result = 1;
for (int i = 0; i < exponent; i++)
{
result *= number;
results[i] = result;
}
return results;
}
call method PowerByArray:
Trace.Write("powers list (by array): ");
int[] powers = PowerCalculator.PowerByArray(2, 10);
foreach (int value in powers)
{
Trace.Write(string.Format("{0} ", value));
}
Trace.WriteLine("");
and next result will be shown:

power_by_array

The way is clear, but it requests to create array. Frequently we cannot allow to create a array, because number of elements and/or size of needed memory.

Usage of yield helps us to avoid creation of array:

static public IEnumerable Power(int number, int exponent)
{
int result = 1;
for (int i = 0; i < exponent; i++)
{
yield return result *= number;
}
}

Calling method Power

Trace.Write("powers list (by array): ");
int[] powers = PowerCalculator.PowerByArray(2, 10);
foreach (int value in powers)
{
Trace.Write(string.Format("{0} ", value));
}
Trace.WriteLine("");

generates next output:

power_by_yield

Reference:

yield (C# Reference)

simple example of yield (reverse)

Loops and iterators in c# (5 ways)

No comments: