C# Tips: Keep it Short, Get it Done - Using “using”
(Page 3 of 4 )
The “using” statement is one of the best ways to see to it that resources are properly disposed of. This construct effectively provides a “try/finally” statement in which the object referenced directly by the “using()” clause is explicitly disposed of in the finally block. The following two examples will produce basically the same IL and have the same effect.
MyClass obj = null;
try
{
obj = new MyClass();
obj.DoSomething();
}
finally
{
if (null != obj)
obj.Dispose();
}
using (MyClass obj = new MyClass())
{
obj.DoSomething();
}
In both cases, “obj” is local to the block in question, though it is clear that “using” requires writing less code and spares us the trouble of explicitly disposing of that object. Remember, even though the garbage collector should be able to rely on your object finalizers as a hook for the “Dispose()” method, you should still code defensively and be certain that objects are properly disposed of yourself whenever possible.
The “using” statement can be nested just like “try” statements. For example, suppose you are trying to create a “DataReader” to bind to an ASP.NET grid. For the sake of brevity, non-relevant code is omitted.
protected DataGrid MyGrid;
private void Page_Load(object sender, System.EventArgs e)
{
using (SqlConnection dbCxn = new SqlConnection(“connection
string”))
{
dbCxn.Open();
string sql = “SELECT * FROM MyTable”;
using (SqlCommand dbCmd = new SqlCommand(dbCxn, sql))
{
using (DataReader reader = dbCmd.ExecuteReader(CommandBehavior.CloseConnection))
{
MyGrid.DataSource = reader;
MyGrid.DataBind();
}
}
}
}
In this example, if we encounter failure at any point while connecting to the database, querying the database, or binding the data, the grid will simply not be databound. All of the objects will be properly disposed of when the “using” statement is exited. Exiting the statement happens when all the code inside the statement has run or when an exception is thrown.
Can you see a potential problem with the “using” statement? What if you try to use an object that does not support the “IDisposable” interface? Well, you simply cannot do that. To use an object in a “using” statement, that object must implement “IDisposable.” I am referring to the object appearing in the actual “using ()” portion, not in the inner block code; you can do whatever you like there.
Note that you do not have to define the object in the “using ()” block, but I recommend it. Unless for some reason you need to use the object outside the scope of the “using” statement, always declare and initialize the object within the “using ()” block itself.
Next: Using “as” and “is" >>
More C# Articles
More By David Fells