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.