Using the C# generic cache: the Tester Doer pattern

In a previous post, I wrote about a generic cache class that I frequently use. I offered the code freely without providing any example use cases. The pattern that I use involves a Boolean test and the value returned in an out parameter. I googled the pattern and it in fact has a name, the “tester doer” pattern.

Let’s look an an over simplified example where we are checking the cache for a value stored in a key named “foo”.

            string foo = null;

            // test to see if we have the value in the cache already
            if(!Cache.Get("foo", out foo)) {

                // since we're here, it's obvious the cache doesn't yet have this stored

                // set the variable foo first
                foo = "bar";

                // let's store it in the cache as well
                Cache.Set("foo", foo);


            // if we got here without ever going into the if block, our implementation of the cache
            // provider took care of setting the out parameter "foo"

            // in either case, we can now be assured that cache value for the foo key has been stored in the foo variable.

            // do something fun with that variable!


One thought on “Using the C# generic cache: the Tester Doer pattern

  1. Pingback: Simple generic C# caching class (I use this all the time) ← Code is Hard

Leave a Reply

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

You are commenting using your 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