Yield Keyword C# with IEnumerable


Used in an iterator block to provide a value to the enumerator object or to signal the end of iteration.

expression is evaluated and returned as a value to the enumerator object; expressionhas to be implicitly convertible to the yield type of the iterator.

The yield statement can only appear inside an iterator block, which might be used as a 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.

yield statement cannot appear in an anonymous method. For more information, seeAnonymous Methods (C# Programming Guide).

When used with expression, a yield return statement cannot appear in a catch block or in a try block that has one or more catch clauses. For more information, seeException Handling Statements (C# Reference).

using System;
using System.Collections.Generic;
 
public class MyClass
{
    public static  IEnumerable<int> Powers(int from,int to)
    {
        for (int i = from; i <= to; ++i)
        {
            yield return (int)Math.Pow(2, i);
        }
    }
 
    static void Main()
    {
        IEnumerable<int> powers = Powers(0, 16);
        foreach (int result in powers)
        {
            Console.WriteLine(result);
        }
    }
}
Source :MSDN
Advertisement

About bpostaci
Escalation Engineer in Microsoft.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: