Some items are scarce resources, they should be properly handled and as soon as they are no longer needed they should be told to "close everything you opened down, and throw yourself away". Generally, these object implement IDisposable: and you can call Dispose on them to activate a destructor to close them down and release all resources.
The
using
block helps with this: it does two very handy things.
1) When the code lease the
using
block
by any means - i.e. by normal means such as dropping to the line after the block, returning from the method, or by means of an Exception being thrown, the system will automatically call Dispose for you - It's like an implicit
finally
block of a
try
, if you like.
2) The scope of the item declared in the
using
block is limited to that block, it cannot be used outside as it no longer exists and cannot be referenced.
using (MyClass ImOKInsideTheBlock = new MyClass())
{
ImOKInsideTheBlock.DoSomething();
}
ImOKInsideTheBlock.DoSomething();