There are two uses of the keyword.
One is when you are too lazy to type System.Web.UI.WebControls.TextBox
you add using System.Web.UI.WebControls
at the top of your code file and henceforth just write TextBox
. That's all it does - shortens the code you have to write (and makes it easier to read).
The other one has to do with the IDisposable
interface. This interface is for objects that need to be cleaned up after you are done using them. Like files, that need to be closed, or DB connections, or that kind of stuff. You could just simply place a call to the Dispose()
method yourself wherever needed, but this makes it easier. In short, this:
using (var X = new MyObject())
{
// Code goes here
}
is equivalent to this:
var X = new MyObject();
try
{
// Code goes here
}
finally
{
if ( X != null )
X.Dispose();
}
Again - it's a shorthand for a piece of code that ensures, that no matter what happens, the Dispose()
method will get called. Even when your code throws an exception, or you return
out of the method, the Dispose()
method will get called. This ensures that you don't accidentally leave files open or something.
In general, if you ever use an object that implements the IDisposable
interface, place it in a using
block.