DCSIMG
Using "using" with a method - IronShay

Using "using" with a method

This is a coding technique I've learned today from looking at Rhino mocks Playback() method code.
It's a nice and smooth technique and I can think of several uses for it.

Consider the following code:

public static void DoSomething()

{

    TimerClass timer = new TimerClass();

 

    using (timer.CountTime())

    {

        string s = "hello world";

        for (int i = 0; i < 100000; i++)

        {

            int index = s.IndexOf("world");

        }

    }

}

This code will result in writing to the console: "Total time: 110ms".
How is it done?

public class TimerClass

{

    public IDisposable CountTime()

    {

        return new MyTimer();

    }

 

    private class MyTimer : IDisposable

    {

        int start;

 

        public MyTimer()

        {

            start = Environment.TickCount;

        }

 

        public void Dispose()

        {

            Console.WriteLine("Total ms: {0} ms", (Environment.TickCount - start));

        }

    }

}

The "secret" is returning an inner disposable class that will take care of what you need...

Hope you've been enlightened,
Shay.

Share this post : del.icio.us it! digg it! dotnetkicks it! technorati!
Published Sunday, June 29, 2008 10:38 PM by shayf

Comments

# Using

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Sunday, June 29, 2008 10:41 PM by DotNetKicks.com

# re: Using "using" with a method

Good technique

Monday, June 30, 2008 10:20 AM by אוהד אסטון

# re: Using "using" with a method

Nice :)

Monday, June 30, 2008 8:31 PM by Maxim

# re: Using "using" with a method

You can also use this technique for capturing and restoring state before and after doing some work, as I've shown here: blog.functionalfun.net/.../misusing-idisposable-beyond-resource.html

Monday, July 07, 2008 11:35 AM by Samuel Jack

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: