The C# using statement explained


A colleague emailed me this week enquiring about the usage for the C# using statement for some code refactoring he was working through.  Now, I don’t mean the ‘using’ directive used to import namespace references at the top of your code, I’m talking about the statement used with your methods.  First a bit of history, then theory.  The statement itself has been around since the release of C#.NET, I have an old Microsoft Press .NET text book from 2002 and it mentions using this statement, so its certainly nothing new.  To understand the purpose of the using statement, you need to be familiar with the two methods of unmanaged memory deallocation.

Garbage Collection

The .NET framework is pretty good as looking after your code for you during execution.  When your applications create objects, some memory space (on the managed heap) is put aside and when objects are finished with and references to them on the heap no longer exist, the CLR will give you a hand and destroy these objects for you without you having to worry about memory management unlike the old days.  It’s called Garbage Collection and its been around for years (Java has done it for longer).

Finalize()

When the CLR destroys your objects, it looks for code in a destructor method in your object and then implicitly calls the Finalize() method.  You cannot call the Finalize() method directly, so you should read up on implementing destructor’s if I’m losing you here.  As a developer you release any unmanaged resources in your destructor method so that the garbage collection process can do this as it implicitly calls the Finalize() method.  Think of creating a destructor as a ‘catch all’ backup.  What I mean is, you are essentially relying on the CLR to invoke the Finalize() method and release your unmanaged resources. It’s implicit and you don’t know when it will happen.  The alternative (and best) approach when working with unmanaged resources is to explicitly release the resource there and then once you have finished with it in your code.  This way the deallocation of unmanaged memory is immediate.  This is where the Dispose() method comes into play.

Dispose()

If you think about .NET objects that work with external resources such as databases, files, network streams etc, you may notice that they implement the System.IDisposable interface. This interface implements the Dispose() method, which explicitly deallocates the memory for the unmanaged resource it is designed to work with.  Take the System.Data.SqlClient.SqlConnection object for example, this works with an external resource that is out of the reach of the garbage collection process (and so no Finalize() method is involved).  The IDisposable interface is very basic in that in contains only one void method that takes no arguments… you guessed it, Dispose().

The Using Statement

Microsoft have a great to the point explanation of what the using statement does – ‘Defines a scope, outside of which an object or objects will be disposed’. Its right on the money.  You create objects within the using statement that once the using statement is complete are disposed of.  The using statement implicitly calls the Dispose() method of the objects being used. I guess common sense is telling you here that you can only use the ‘using’ statement with objects that implement IDisposable!

The code example below demonstrates the use of the statement with the SqlConnection object we mentioned above.  Once this method returns the data requested in the passed in SQL query, the using method calls the Dispose() method on the SqlConnection object (I should point out at this point that you pass more than one object to the using statement):

Tip – When the compiler turns the using statement into MSIL it creates Try and Finally blocks for the code.

Advertisements

One comment

  1. SqlCommand and SqlDataReader both implement IDisposable so you should be using the ‘using’ statement with those as well.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s