Posted by: Cirilo Meggiolaro | 11/4/2008

Tip of the day #21 – Yield keyword

The yield keyword may be used only in an iterator block to retrieve items individually to the enumerator object.

In practice you don’t need to create and populate an object that implement the IEnumerable interface before you return the collection. You just need to retrieve the items from the iterator method.

You may use the yield keyword to return value or to break the iterator processing like in the following example:

static void Main(string[] args)
foreach (int i in MyMethod(200, 5))


public static IEnumerable MyMethod(int upperBound, int increment)
int result = 0;

while (result < upperBound)

if(someCondition) yield break;
result += increment;
yield return result;


  1. Hey, I did not see thit tip before!

Leave a Reply

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

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s


%d bloggers like this: