Codeless: C# Keywords - yield - Iterators without classic iterator code

Oscar Brito

Codeless with c#:
        public static IEnumerable GetThings()
        {
            List<int> col = new List<int>();

            for (int i = 0; i <= 100; i++)
            {
                col.Add(i);
            }

            return col.AsEnumerable();
        }

        public static IEnumerable GetThingsBetter()
        {
           
            for (int i = 0; i <= 100; i++)
            {
                yield return i;
            }

        }


        [TestMethod]
        public void Yield_Keyword()
        {
            List<int> i1 = new List<int>(GetThings().Cast<int>());
            List<int> i2 = new List<int>(GetThingsBetter().Cast<int>());

            Assert.AreEqual
                (
                i1.Count,
                i2.Count
                );
        }

From Msdn:

"The yield keyword signals to the compiler that the method in which it appears is an iterator block. The compiler generates a class to implement the behavior that is expressed in the iterator block. In the iterator block, theyield keyword is used together with the return keyword to provide a value to the enumerator object."

Let's see how it can be used:

"The yield statement can only appear inside an iterator block, which can be implemented as the body of a method, operator, or accessor. The body of such methods, operators, or accessors is controlled by the following restrictions:

  • Unsafe blocks are not allowed.

  • Parameters to the method, operator, or accessor cannot be ref or out.

  • A yield return statement cannot be located anywhere inside a try-catch block. It can be located in a try block if the try block is followed by a finally block.

  • A yield break statement may be located in a try block or a catch block but not a finally block."



Visit www.divhide.com for more informations, contacts and news about Web Development.
See other blog posts at blog.divhide.com.

Divhide purpose is to follow the HTML5 movement and contribute with applications which prove the quality of technology.
Feel free to contact divhide.