The "using" pattern

In the previous post, I’ve discussed how I misused the IDisposable.Dispose() method. Here, I will present some of the ways I use the using keyword in manners that may don’t come to mind at first (I may in a few years come back to this and realize I was totally wrong, but for now, it seems to me the samples provided here may prove usefull).

According to msdn, the using statement “Defines a scope, outside of which an object or objects will be disposed“. In the remarks section of the documentation, it is also stated that “The using statement allows the programmer to specify when objects that use resources should release them“. And the next sentence: “The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object’s resources“. Everything’s ok about all this, expect one little thing: by insisting on resources, it drives people to use the using keyword only with objects holding resources, or locks, or connections or whatever needs to be released to the system…

I think this statement can be used in an extensible manner for any object that:

  • lives in a finite scope
  • needs an action to be done when created and another one when you don’t need it any more.

For instance, when it’s dark, and I want to write something, I need some light. So I turn it on, write my post, and turn it off before going to bed. This could be writtent this way in C#:


There are times when I’m quite tired, and I may forget to switch off the light before going to bed. This results in this code:


Here, C# programmers will have recognized that some kind of Dispose() call is missing. Enters the using keyword which allows me to write:



And thus, I never forget to turn off the light before going to bed.

I really like the metaphor the using keyword provides, and I’d like to be able to use it even for objects that don’t hold any system resource. As the samples below demonstrate it, there’s nothing preventing me from doing so. The main idea is that any object that needs to do something when created, and something else when released is a good candidate for the using keyword: these two tasks are implemented in the constructor and in the IDisposable.Dispose() method. The task executed in the Dispose() method hasn’t to release resources. In fact, most of the times, It just restores a saved state.

Example 1:

In most of my windows forms applications, I use a base form class providing some goodies to inheritors (one of them is a wonderfull linear gradient I apply on the background of my forms – question of taste). Among these services is WaitCursor. Usually when you want to show an hourglass cursor while processing a lengthy task, you have to follow three steps:

  1. Change the cusor: this.Cursor = Cursors.WaitCursor;
  2. Execute the lengthy task in a try block
  3. Restore the normal cursor in a finally clause: finally { this.Cursor = Cursors.Default; }

I’ve built up a little helper class (completed with a property) which allows you to write this code, (which seems more readable to me : it’s almost well formed English):

using(WaitCursor) { /* execute lengthy task */ }

First, in the base form class, WaitCursor is a property returning an IDisposable:

protected IDisposable WaitCursor
         get { return new CursorProvider(this, Cursors.Wait); }

And CursorProvider is a private inner class also defined in the base form class:

private class CursorProvider : IDisposable
        Control owner = null;
        Cursor savedCursor = Cursors.Default;

        public CursorProvider(Control control, Cursor newCursor)
            if (control == null)
                throw new ArgumentNullException(“control”);
            if (newCursor == null) 
                throw new ArgumentNullException(“newCursor”);

            owner = control;
            savedCursor = control.Cursor;
            control.Cursor = newCursor;

        #region IDisposable Members

        public void Dispose() { owner.Cursor = savedCursor; }


A few explanations:

  • The property is returning an IDisposable instance: indeed, callers don’t have to know anything else (it is intendeed to be part of a using statement) so, why would I expose more?
  • Each time the property is called, a new object is created: you can overlap as many using statements as you wish, after the last closing bracket, the correct cursor will be restored.
  • We never need the object created by the call to the property, thus the using(WaitCursor) and not some using(IDisposable foo = WaitCursor).
  • The class is straightforward: the constructor, after checking for null parameters, saves the current state (the current control’s cursor) then sets the new state. Inside Dispose() (which will always be called at the end of the using block, wether an exception has been thrown or not), the state is restored.

Example 2: Saving the state of a Graphics object. In this old post, I exposed a way of using the GraphicsContainer class. And I wrapped it in an IDisposable object (one time again, the idea is to save a state in the constructor, and to restore it in Dispose()).

Example 3: .NET Matters: Scope and more. In this article from MSDN Magazine, Stephen Toub explains how to code a Scope<T> class to provide transactionnal behavior. This is an advanced example of a class that fits perfectly well with the using syntax. Besides the link with this post regarding the using statement, this article also discusses many other interesting .NET concepts (and in particular, the notion of thread static members). The second short article about the Semaphore class is again an example of a pretty use of the using statement.


3 thoughts on “The "using" pattern

  1. I like it…

    Of course, I would do things a different way. I’d rather use directly the CursorProvider class:
    using(new CursorProvider(this, Cursors.Wait)) { … }

    For lazy people -like me- this class would be overloaded (WaitCursorProvider for instance).

    I’m not very keen in using a WaitCursor property inherited by the Form.

    The problem is always the same: a class only has a single inheritance relation. Using for something as little as the WaitCursor property looks like waste to me. What if you want to use a super-dialog-box-with-lots-of-features?

    I really think, when you want to develop re-usable features, that you should try to save the only inheritance relation.

    But this is philosophy… I really like the idea of using IDisposable this way!

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 )

Google+ photo

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


Connecting to %s