Have you ever tried using  the "Using" statement with a method and not a class?

We all have done the following:

   1: using(StreamReader s = new StreamReader(@"c:\Test.txt"))
   2: {
   3:     // Do stuff
   4: }

Whether you know it or not, the compiler translates that code to the following:

   1: StreamReader reader = new StreamReader("MyFile.txt");   
   2: try  
   3: {   
   4:     // Do Stuff
   5: }   
   6: finally  
   7: {   
   8:     if (reader != null)   
   9:     {   
  10:         ((IDisposable)reader).Dispose();   
  11:     }   
  12: }  

And while doing that makes sure that the Dispose method is called so files and data base connections are closed and so on. Why not take the "Using" statement and make it more useful. The Dispose method we want to be called does not have to Dispose of stuff, it can do anything we want!

Lets see how we can do this. Suppose you have an operation that and we want to know how long it takes. all we have to do is the following:

The Main:

   1: static void Main(string[] args)
   2: {
   3:     OperationTimeCounter timer = new OperationTimeCounter();
   5:     using (timer.StartCounting())
   6:     {
   7:         for (int i = 0; i < 100000; i++)
   8:         {
   9:             int index = i * 34 / 23;
  10:         }
  11:         for (int i = 0; i < 100000; i++)
  12:         {
  13:             int index = (int)Math.Pow((double)i, 23.0);
  14:         }
  15:         // and a whole lot of stupid operations... :)
  16:     }
  17: }

Look at the Using Statement we are "Using" a Method not a class.

Look at the Counting Class:

   1: public class OperationTimeCounter
   2: {
   3:     public IDisposable StartCounting()
   4:     {
   5:         return new TimeCounter();
   6:     }
   8:     private class TimeCounter : IDisposable
   9:     {
  10:         int StatTickCount;
  11:         public TimeCounter()
  12:         {
  13:             StatTickCount = Environment.TickCount;
  14:         }
  16:         public void Dispose()
  17:         {
  18:             Console.WriteLine("All your stupid operations took: {0} ms"
  19:                             , (Environment.TickCount - StatTickCount));
  20:             Console.ReadLine();
  21:         }
  22:     }
  23: }

As you can see the OperationTimerCounter class returns a IDisposable TimeCounter Class which logs the start time TickCount. when we exit the scope the Dispose method is called and the subtraction is printed to the console. Great isn’t it?

I think it is very useful, although muse be handled with care or it can turn into a mess.

To download a Sample Project Check out the bottom of our RSS feed for the password to the Freebies page

Tags :

22 Responses to “Using The "Using" Statement On a Method Rather Than a Class”

  1. James Curran

    Said on July 31, 2008 :

    I’ve checked out the RSS feed, and found the password, but the freebie page isn’t accepting it.

  2. James Curran

    Said on July 31, 2008 :

    Cool idea, but you seem to be going through a bit of extra effort. Why not make StartCounting() a static method:

    using (OperationTimeCounter.StartCounting())

    That cuts out one line and a needless variable.

    Or we could go the other way, and make TimeCounter public:

    using (TimeCounter timer = new TimeCounter())

    This gives more of the classic using syntax, while simplifying the code.

  3. Justin

    Said on July 31, 2008 :

    Why not make the timer a public class and use it directly, seems much simpler.

  4. Shahar Y

    Said on July 31, 2008 :

    @ James Curran
    There are problems with Firefox and wordpress passwords. We are looking for a way out of this problem, currently try doing it with IE, it will work just fine.

  5. Chris Marisic

    Said on July 31, 2008 :

    The first question was asked, “can I do this?” The answer is yes it’s possible (as is most everything in the world), now the question is “SHOULD I do this?”

    I would never recommend implementing a model using this coding method. Leave dispose for solely cleaning up your objects. I don’t think this road should ever be traversed upon. The same way exception throwing and catching should never be done to handle ordinary logic flow.

  6. steve

    Said on July 31, 2008 :

    I think this is a horrible idea. It’s just going to confuse the next guy who comes along and has to maintain this code.

  7. Steve

    Said on July 31, 2008 :

    And if you aren’t using the timer instance you can just do:

    using (new TimeCounter())

  8. Ang3lFir3

    Said on July 31, 2008 :

    This isn’t really using “Using” on a method.

    The compiler will call the StartCounting() method which returns the TimeCounter as an IDisposable.

    Implementing IDisposable is all that is needed for the compiler to know that it can call dispose on the object. No matter what it is.

  9. B.Dion

    Said on July 31, 2008 :

    Sure. And why don’t you overload the + operator to add a record in a database?

  10. Tom Willis

    Said on July 31, 2008 :

    Yep, I do this as well for putting timing around arbitrary code blocks. Also nice for keeping transaction mgmt code all clean…

    using(var t = new MTransactionContext())
    //a bunch of stuff

    class MTransactionContext
    private Transaction _Tran;
    private bool _Commit;

    public MTransactionContext()
    this._Tran = new Transaction();

    public void Commit()


    public void Dispose()


    //or something that actually works like that :)

  11. Gavin

    Said on July 31, 2008 :

    You can use this method to write a class that can make sure the state is restored to it’s previous point, for example with WaitCursors:

    public class CursorSaver {

    private Control Control;

    public CursorSaver(Control control) {
    Control = control;

    public IDisposable Wait() {
    Cursor old = Control.Cursor;
    Control.Cursor = Cursors.WaitCursor;
    return new CursorSaverHelper(() => Control.Cursor = old);

    private class CursorSaverHelper : IDisposable {

    private MethodInvoker OnDispose;

    public CursorSaverHelper(MethodInvoker method) {
    OnDispose += method;

    public void Dispose() {



    Then you can use it like:

    using (ChangeCursor.Wait()) {
    // do work here

    (Haven’t checked to see if it compiles, hope it works.)

  12. Amit

    Said on July 31, 2008 :

    @ Everyone :)

    I agree this is a very unmaintainable code, and not my idea of good simple programming. I just think it is a nice trick that can be helpful sometime.

  13. Amit

    Said on August 1, 2008 :

    For what it’s worth, I like the idea of thinking up handy constructs. Using could’ve been taking further by i.e. allowing multiple different resources to be handles rather than only multiple variables with the constraint that they be of the same type.

  14. Michael Hall

    Said on August 1, 2008 :

    Please don’t take this the wrong way, but this pattern was demonstrated several months ago in a similar manner. You might like to check out this posting. http://www.dotnetkicks.com/tipsandtricks/Stopwatch_Writer_Simplify_Your_Performance_Testing. FWIW, don’t listen to the haters used judiciously and well commented this pattern can make for some clean code. I use it to help log the entry and exit points for critical methods and it’s much cleaner than inserting the same logging details everywhere. DRY!

  15. Ryan Martin

    Said on August 1, 2008 :

    Classic case of trying to be too clever.
    Yes, it’s kind of neat that you can use dispose to do what you want.
    No, it shouldn’t be used because it confuses the reader. Dispose is very clear in it’s purpose. People are expecting it to act as such.
    You’re just asking for a world of pain.

  16. Amit

    Said on August 1, 2008 :


    Not taking it the wrong way :)

    I bet if you look it up you will find similar stuff more than once, and that goes for every post of every blog out there.

    I can asure you I am not stealing content. its all me :)

  17. wekempf

    Said on August 1, 2008 :

    The BCL already makes use of this concept. Many collection types have a SimpleMonitor class that maintains a call count that’s decremented in the Dispose method, which is used by CheckReentrancy() and BlockReentrancy() calls. The BlockReentrancy() call returns the monitor and is wrapped in a using statement.

  18. Michael Hall

    Said on August 1, 2008 :

    Absolutely, I wasn’t making any implications of impropriety on your part. Just thought you might be interested in similar points of view. :-)

  19. Vhaerun

    Said on August 4, 2008 :

    When will the #13 programming challenge comments will be approved ?

  20. Shahar Y

    Said on August 4, 2008 :

    @ Vhaerun
    tomorrow we will publish a new challenge and approve #13 comments, sorry for the delay.

  21. web design company

    Said on August 19, 2008 :

    pedantry… You’re always using “using” on an object that implements the IDisposable interface; you don’t really use it “on a class” or “on a method”. (That aside, I’ve used this “return an IDisposable from a method” idiom before and it can be useful.)

1 Trackback(s)

  1. Sep 11, 2008: DEV102 - AUGUST 2008 BLOG STATS | Dev102.com

Post a Comment