As some people already noted, using
wraps the IDisposable
interface, as in:
using (var foo = new MyDisposable()) { ... }
is the same as:
var foo = new MyDisposable()
try {
...
}
finally {
if (foo != null) { foo.Dispose(); }
}
So far so good. The reason that C# implements this is because of unmanaged resources. Why? Unmanaged resources require you to clean up the stuff at a time you want, instead of a time that the Garbage Collector (GC) wants (which is f.ex. when you run out of memory).
Consider the alternative for a moment: let's assume you have a file. You open the file, write some bytes, forget 'close' and then don't have IDisposable to close it. Your file will continue to be open, even though you don't use the object anymore. Even worse, you don't even know that data has been written if your program exits. If your program runs long enough, at some point the GC will probably kick in and remove the thing for you, but until then every other attempt to open the file will probably give you a big, fat error. So, in short...: a lot of pain and misery.
And this is what IDisposable
solves.
Connections, files, memory access, network access, ... basically everything that uses stuff that needs to be cleaned up implements IDisposable
. It even holds true that if a type implements IDisposable
, you'd better Dispose it.
So... SQL connections implement IDisposable, SQL Readers implement IDisposable, and so forth. Personally, I tend to check every type for the presence of an IDisposable interface, before working with it (so yeah that is: all the time).
Once you understand this, the correct way to use all this is obvious:
using (var sourceConnection = new SqlConnection())
{
sourceConnection.Open();
using (var destinationConnection = new SqlConnection())
{
destinationConnection.Open();
// ...
using (var myReader = srcConnection.ExecuteReader(...))
{
// ...
}
}
}
... and so on.
Now, in some cases you obviously cannot use using
because you're using different methods. How to solve this? Easy: Implement the Dispose Pattern in the class that has these methods.
More information (as well as the Dispose pattern): https://msdn.microsoft.com/en-us/library/b1yfkh5e(v=vs.110).aspx