The using
statement
using(var your_object = new object_that_implements_IDisposable()) { ... }
is syntactic sugar for the following:
var your_object = new object_that_implements_IDisposable()
try
{
...
}
finally
{
((IDisposable)your_object).Dispose();
}
This is only applicable for classes that implement IDisposable. It is helpful for cleaning up code where you have objects that take, for example, system resources (file handles, database connections, sockets, etc.) that need to be cleaned up after you are done to free the resource for the rest of the system.
In theory, you could leave out the .Dispose()
call, but then you would have to wait for the Garbage Collector to free the kept resources. The GC is awesome at knowing when to free objects to reclaim their memory usage, but it has no idea that it needs to free objects to have them give up other system resources. Thus, these critical resources might not be given up until after the GC decides it needs the memory used by the owner. Thus, you definitely want to dispose of your objects when you are done with them (if they are disposable)!
As to why you'd use using
over try
/finally
, it is purely a coder's preference. I prefer using
because you can cascade them:
using(var a = new class())
using(var b = new class())
using(var c = new class())
using(var d = new class())
{
...
}
You'd need quite a few more lines of code to do that with try
/finally
.
See also: