Possible Duplicate:
What is the C# Using block and why should I use it?
I'm converting an old site to C# and I'm not sure when I should be using 'using'. Are there any general guidelines? I know of the benefits, but I'm not 100% sure how to use it. Is it every time I 'new' a method/property?
SqlConnection awesomeConn = new SqlConnection(connection);
If a class implements
IDisposable
then it will create some unmanaged resources which need to be 'disposed' of when you are finished using them. So you would do something like:To avoid forgetting to dispose of the resourses (in this case close the database connection), especially when an exception is thrown, you can use the
using
syntax to automatically call dispose when you go out of the using statement's scope:In fact, the using block is equivalent to:
Using is a convenience that allows you to assure that you can't exit a block with out disposing of the resource. It can and should be utilized whenever you have to utilize an IDisposable implementer in a local code block.
Use using for all objects which you instantiate that implement IDisposable unless their lifetime extends beyond the current scope of execution (I.e. method call). In that case, for instance if you have a disposable member variable, then the containing class should implement IDisposable and Dispose members in its Dispose.
It is often used if you want to automatically dispose objects. Otherwise you have to call myobj.Dispose() manually.
See the reference documentiation here: http://msdn.microsoft.com/en-us/library/yh598w02.aspx
MSDN:
Example: