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)call method PowerByArray:
{
int[] results = new int[exponent];
int result = 1;
for (int i = 0; i < exponent; i++)
{
result *= number;
results[i] = result;
}
return results;
}
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:
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:
Reference:
No comments:
Post a Comment