using Statement in c# - ablealias/asp.net GitHub Wiki
using statement
provides a convenient syntax that ensures the correct use of IDisposable object.
using (Font font1 = new Font("Arial", 10.0f))
{
byte charset = font1.GdiCharSet;
}
using statement commonly used when a managed types that access unmanaged resources. All such types must implement the IDisposable
interface. When the lifetime of an IDisposable object is limited to a single method, you should declare and instantiate it in a using statement
. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.
You can instantiate the resource object outside the using statement and then pass the variable to the using statement, but this is not a best practice. In this case, the object remains in scope after control leaves the using block even though it will probably no longer have access to its unmanaged resources. In other words, it will no longer be fully initialized. If you try to use the object outside the using block, you risk causing an exception to be thrown. For this reason, it is generally better to instantiate the object in the using statement and limit its scope to the using block.