11 Sep

C# yield keyword

If we use the yield keyword in a statement, we indicate that the method, operator, or get accessor in which it appears is an iterator.

Two forms of the yield statement are used.

   yield return <expression>;
   yield break;

We use a “yield return” statement to return each element one at a time.
We use a “yield break” statement to end the iteration.

Usage :

            // Display powers of 2 up to the exponent of 10: 
            foreach (int i in Power(2, 10))
            {
                Console.Write("{0} ", i);
            }
            // Output: 2 4 8 16 32 64 128 256 512 1024

Sample :

        public System.Collections.Generic.IEnumerable <int> Power(int number, int exponent)
        {
            int result = 1;
            for (int i = 0; i < exponent; i++)
            {
                result = result * number;
                yield return result;
            }
        }

Leave a Reply

Your email address will not be published. Required fields are marked *