Welcome to MSDN Blogs Sign in | Join | Help

yield return

Here's a .NET 2.0 language feature I discovered recently: "yield".  It's spectacularly useful in some situations -- to build a pipeline of lazy iterators, for example -- but also neat enough I'm using it all over.

One example where it actually is the right thing to do, not just syntactic sugar, is where you want an enumerator but constructing each item is quite expensive.  Here's partial code for a class which returns an enumeration of file attachments on a SharePoint list entry:

public class MyListItem
{
    // ... stuff ...
    // 'Attachment' is a simple struct with name and fileContents
    public IEnumerable<Attachment> Attachments
    {
        get
        {
            // Read the attachment from this list item
            WSSListsWebSvc.Lists listsService = _listsService.Open();
            System.Xml.XmlNode attc = listsService.GetAttachmentCollection(_listName, ID);
            // Walk the attachment collection and return content
            foreach(XmlNode attn in attc.ChildNodes)
            {
                string url = attn.InnerText;
                int n = url.LastIndexOf('/');
                string filename = url.Substring(n+1);
                Attachment att = new Attachment(); 
                att.name = filename;
                System.Net.WebClient client = new System.Net.WebClient();
                client.Credentials = _listsService.credentials;
                att.fileContents = client.DownloadData(url);
                yield return att;
            }
            yield break;
        }
    }
}

The caller to consume this sequence of attachments is incredibly simple:

        foreach (Attachment att in listItem.Attachments)
        {
            // do stuff with the attachment
        }

There's a long MSDN Magazine article covering this and several other topics; if you're developing with .NET, definitely worth a read.

Published Wednesday, March 29, 2006 10:25 AM by hpyle

Comments

No Comments

Anonymous comments are disabled
 
Page view tracker