The Ultimate Disposable

time to read 4 min | 739 words

I'm very partial to safe code, so I really like the using() statement in C#. The problem with this statement, however, is that I want to do different things at different times, which require different disposing semantics from the same class. Here is an example from Rhino Mocks:

using(mocks.Ordered())
{
   using(mocks.Unordered())
   {
   }
}

I'm using the using() statement to allow easy scoping of the behavior. I find the code far more readable this way. The problem is that I need to create a class that implements IDisposable, while the action that I want is a single line of code. For this purpose, I created the DisposableAction:

public class DisposableAction : IDisposable
{
  Action<T> _action;

  public DisposableAction(Action<T> action, T val)
  {
     if (action == null)
       throw new ArgumentNullException("action");
     _action = action;
  }
 
  public void Dispose()
  {
    _action();
  }
}

The usage of this class is simple:

public IDisposable AllowModification
{
  get
  {
      _allowModification = true;
      return new DisposableAction(delegate { _allowModification = false; } );
   }
}

And then you can call it like this:

UsuallyReadOnly foo = new UsuallyReadOnly();
using(foo.AllowModification)
{
  foo.Name = "Bar";
}

Simple, safe, and it doesn't require of me to write any more than neccecary.