Fun With C# 2.0 Iterators

In the little free time that I have, I have been messing around with writing a .NET program to help me with the large amount of photo metadata editing I want to do on all the photos I’ve been uploading to my Flickr photostream.

It’s been fun doing some .NET again. It’s easy to forget how nice of a language C# is especially with all of the fancy new features 2.0 brings. Last night, I came up with a fun little method of using iterators.

Simple "Add Photo" dialog box Here’s the scenario: I need to collect photo IDs for editing. As a simple solution, I have a very small dialog box that contains a text field, an “Add Another” button, a “Done” button, and a “Cancel” button. When the user clicks “Add Another,” I want to save the entered photo ID and re-display the dialog. If they click “Done,” the currently entered ID should be saved, and the dialog should vanish. Finally, if they click cancel, the current ID does not get saved, and the dialog disappears.

I have set up the DialogResult of the “Done” buttton to return with DialogResult.OK, and “Add Another” to return with DialogResult.Yes. Here’s the code in the UI controller responsible for coordinating this: public IEnumerable GetPhotoIds() { AddPhotoDialog dialog = new AddPhotoDialog();


DialogResult result = dialog.ShowDialog(this.parentWindow);

while (result == DialogResult.Yes   result == DialogResult.OK) { yield return dialog.PhotoId;

if (result == DialogResult.OK) { yield break; }


result = dialog.ShowDialog(this.parentWindow); } }

Then, in the top-level UI controller, I can simply do: AddPhotoUIController controller = new AddPhotoUIController(this.mainForm);

foreach (string photoId in controller.GetPhotoIds()) { PhotoInfo info = this.FlickrApi.PhotosGetInfo(photoId); this.CurrentBatch.Containers.Add(new SinglePhoto(info)); }

Pretty slick. I wish they had made this feature more general, though, and implemented full-on continuations.