I have read a couple of articles about the using statement to try and understand when it should be used. It sound like most people reckon it should be used as much as possib
Using statement is syntax sugar of C#.
So the following code:
using(var someDisposableObject = new someDisposableObject())
{
// Do Something
}
actualy looks like:
var someDisposableObject = new someDisposableObject();
try
{
// Do Something
}
finally
{
if (someDisposableObject != null)
{
((IDisposable) someDisposableObject).Dispose();
}
}
Look at this article: http://msdn.microsoft.com/en-us/library/yh598w02.aspx
One time I can think of where you wouldn't want to use 'using' on connections would be on ClassFactories for connected objects such as DataReaders, e.g. consider the case
private IDataReader CreateReader(string queryString,
string connectionString)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
return command.ExecuteReader(CommandBehavior.CloseConnection);
// Don't close connection
}
(Modified from MSDN - The example on MSDN is just plain stupid)
Another reason is on WCF ServiceReference 'clients' - if the channel becomes faulted, 'using' then hides the actual exception. But this is just a buggy implementation IMHO.