Languages - DevSource
DevSource: Microsoft Developer Resource DevSource Home Sponsored by Microsoft Home Add Ons Architecture Languages Techniques Using VS Forums
Home arrow Languages arrow C#: Dynamic Iterators with Yield Return
C#: Dynamic Iterators with Yield Return
By Paul Kimmel

Rate This Article: Add This Article To:

C#: Dynamic Iterators with Yield Return
( Page 1 of 3 )

The yield-return construct in C# lets you easily create iterators by exiting and re-entering a for loop. How does this work? Paul Kimmel shows you how to use yield and how it works.

Introduction

In the not-too-recent past I predicted that code generators would produce some of the most exciting and useful innovations. Because code that writes code—once perfected—is perfect every time. Humans cannot get something perfect every time, ever.

One innovation that is sure to grow on you, though not exciting, is very useful. It is the yield return idiom. The word yield when preceding the keyword return (or break) is actually a hint to the .NET framework to kick over the code generating engine.

In this article I will explain how yield return works and show you how to save a little work a lot of time.

Using Yield Return

The yield identifier itself is not a keyword. However, yield immediately before return is a key construct. To use yield return, simply define a function that returns IEnumerable<T>, write a foreach loop as you normally would and use yield return to return to the caller those elements that match some arbitrary criteria. That is, you can use yield return to copy a collection or a subset of that collection.



ADVERTISEMENT

Listing 1 is the Main function of a console application. Supporting code implements a class called ScrabbleWord and a generic List<T> of ScrabbleWord objects, called Dictionary. The basic idea is that Dictionary represents a Scrabble® dictionary. The main loop requests only those words that match the regular expression ^A\w+E$; that is, words beginning with A, ending with E, and having one letter in between.

Click Here for an introduction to Regular Expressions.



Listing 1: The Main function of a console application that is requesting a subset of a Scrabble dictionary.

static void Main(string[] args)
{
  Dictionary d = Dictionary.Create();

  //foreach(ScrabbleWord word in d)
  foreach(ScrabbleWord word in d.Get(@"^A\w+E$"))
    Console.WriteLine(word);

  Console.WriteLine("enter");
  Console.ReadLine();
}


 
 
>>> More Languages Articles          >>> More By Paul Kimmel
 



Microsoft's Future: A Chat With Their CTO, Barry Briggs

Play Video >

All Videos >

Julia explores the Robotics Studio!

Read now >

Messages to Bill Gates!

Read now >

View Now
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.