Another often overlooked C# statement that was introduced in .NET 2.0 is yield. This keyword is used to return items from a loop within a method and retain the state of the method through multiple calls. That is a bit hard to wrap your head around, so as always, an example will help;
public static IEnumerable<int> Range( int min, int max )
{
for ( int i = min; i < max; i++ )
{
yield return i;
}
}
Using this, you can write the following code;
foreach ( int i in Range( 10, 20 ) )
{
Console.Write( i.ToString() + " " );
}
10 11 12 13 14 15 16 17 18 19
Example 2:
static void Main()
{// Compute two with the exponent of 10.
foreach (int value in ComputePower(2, 10))
{
Console.Write(value);
Console.Write(" ");
}
Console.WriteLine();
}
public static IEnumerable<int> ComputePower(int number, int exponent)
{
int exponentNum = 0;
int numberResult = 1;//
// Continue loop until the exponent count is reached.
//
while (exponentNum < exponent)
{
//
// Multiply the result.
//
numberResult *= number;
exponentNum++;
//
// Return the result with yield.
//
yield return numberResult;
}
}
Output:
2 4 8 16 32 64 128 256 512 1024
FYI
The yield is usually used in Enumerator.
No comments:
Post a Comment