This is a mirror of official site: http://jasper-net.blogspot.com/

Great Uses of Using Statement in C#

| Wednesday, June 23, 2010
In my last post about testing emails in .NET, I noted the use of the using statement to ensure safe usage of the IDisposable SmtpClient and MailMessage objects.  This is the typical usage of the using statement, but you can take advantage of this statement’s behavior for other scenarios as well, resulting in cleaner code.

Consider the scenario where you want to perform some kind of pre- and post- processing around an arbitrary block of code.  The simplest scenario I know of is when you want to time some code, using the stopwatch class.  If you want to perform basic stopwatch usage, you can write some code like this (borrowed from the stopwatch MSDN docs):

public static void BasicStopWatchUsage()
{
   Console.WriteLine("Basic StopWatch Used: ");
   var stopWatch = new Stopwatch();
   stopWatch.Start();
   Thread.Sleep(3000);
   stopWatch.Stop();
   TimeSpan ts = stopWatch.Elapsed;

   string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                      ts.Hours, ts.Minutes, ts.Seconds,
                                      ts.Milliseconds/10);
   Console.WriteLine(elapsedTime, "RunTime");
}

This works, and of course the Thread.Sleep(3000); is where our actual work would go.  If our actual work is a relatively small amount of code, it can easily be lost in the clutter that comprises our stopwatch profiling code.

Read more: Steve Smith

Posted via email from .NET Info

0 comments: