Over a million developers have joined DZone.

Bitten by yield return


I like the simplicity of creating enumerations with iterator blocks through yield return. Even though I regularly do it, I was bitten by a nasty bug a few weeks ago and it was entirely my own fault.

I had been working hard on my bar management system, which includes a service to book a bar stool in advance. In my initial design, a booking had to be submitted for each day. During the first user tests, the regulars complained that it was far too complicated. They wanted to book their favorite bar stool with date intervals. The solution I came up with was a helper method that created a series of bookings between two dates.

public static IEnumerable<SubmitSeries>(BarStoolBooking bookingInfo,
    DateTime firstDate, DateTime lastDate)
    for (DateTime date = firstDate; date <= lastDate; date = date.AddDays(1))
        bookingInfo.Date = date;
        yield return bookingInfo.Submit();

 There’s a nasty bug in there. Can you spot it? I didn’t. I was bitten by it later on, when I wrote the presentation layer.

The presentation layer for this is simple, it prints out a header, the dates and then a footer.

var bookings = BarStoolBooking.SubmitSeries(baseBooking,
    DateTime.Now.Date, DateTime.Now.Date.AddDays(1));
foreach (var b in bookings)

I still didn’t see the catastrophic error I had made. Can you spot it?

I found out when I saw the generated order numbers.

42 is booked for Arthur Dent (ref no 1) the following dates:
End of dates (ref no 4)


The header uses ref no 1. The footer uses ref no 4, but they should be the same number…

The problem is the lazy evaluation of the iterator block produced with yield return. It will be evaluated three times, although two of them only will evaluate the first object.

  1. When PrintHeader(bookings.First()) is called (just the first element)
  2. By the foreach statement (entire sequence)
  3. When PrintHeader(bookings.First() is called (just the first element)

On each evaluation, a new booking is submitted.

I was bitten by the lazy evaluation of yield return. The lesson learned? Never use yield return if there are side effects (such as submitting a booking…)


Published at DZone with permission of Anders Abel, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}