I'm not talking about references to assemblies, rather the using statement within the code.
For example what is the difference between this:
using (DataReader dr = .... )
{
...stuff involving data reader...
}
and this:
{
DataReader dr = ...
...stuff involving data reader...
}
Surely the DataReader is cleaned up by the garbage collector when it goes out of scope anyway?
The point of a using
statement is that the object you create with the statement is implicitly disposed at the end of the block. In your second code snippet, the data reader never gets closed. It's a way to ensure that disposable resources are not held onto any longer than required and will be released even if an exception is thrown. This:
using (var obj = new SomeDisposableType())
{
// use obj here.
}
is functionally equivalent to this:
var obj = new SomeDisposableType();
try
{
// use obj here.
}
finally
{
obj.Dispose();
}
You can use the same scope for multiple disposable objects like so:
using (var obj1 = new SomeDisposableType())
using (var obj2 = new SomeOtherDisposableType())
{
// use obj1 and obj2 here.
}
You only need to nest using
blocks if you need to interleave other code, e.g.
var table = new DataTable();
using (var connection = new SqlConnection("connection string here"))
using (var command = new SqlCommand("SQL query here", connection))
{
connection.Open();
using (var reader = command.ExecuteReader()
{
table.Load(reader);
}
}