The Power of Yield Return

David Cooksey: Using code yield return

February 19th 2009 | David Cooksey

The Power of Yield Return

While working on a project recently I ran into a problem that was very difficult to track down.  We have a good number of checks that validate business rules on the main business object within the system.  Sometimes these checks need to run on related business objects as well.  The problem comes into play at this point, because the checks at the time of their creation do not have a direct reference to the business object they will be run on.  Since the checks have dependencies that vary with their intended target, the convention is to push an Id onto a static stack, create the checks, run the checks, then pop the Id off of the stack.

Unfortunately, it is very easy to forget to update the stack, or to push but not pop. This results in some checks being set up and then run using the wrong dependencies, which causes all kinds of obscure behavior down the road.

Enter Yield Return.

This is a simple wrapper that guarantees the StaticStack is updated correctly.  Even if the calling code throws an exception, the Pop() function will still be called.  Note that the real code uses a context-specific stack, the sample code presented here does not handle multi-threaded situations.

Any foreach statement that iterates over a collection of business objects can then be updated as follows.

What I find most interesting about this pattern is that it allows the called function to run any arbitrary setup or teardown code per object it returns, in synch with the caller’s processing of the object.


David Cooksey is a Senior .NET developer at Thycotic Software Ltd.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: