Using keyword “using” in code block March 3, 2007
Posted by addisu in Software - .NET 2.0, Software - .NET General, Software - ASP .NET 2.0, Software - C#.trackback
Recently, I have been asked about the alternative way to Dispose objects as we often do in the “finally” block in “Try .. Catch .. Finally” block for connection object. I have seen “using” keyword in some sample codes but I never aware of it does dispose the objects declared as “using“
Example:
using (IDataReader dataReader = _db.ExecuteReader(“GetCategories”))
{
// Processing code
while (dataReader.Read())
{
Category item = new Category(
dataReader.GetInt32(0),
dataReader.GetString(1),
dataReader.GetString(2));
this.cmbCategory.Items.Add(item);
}
}
- One thing to note is the objects inside the “using” block should implement “IDisposable” interface.
- Still if we want to cache Exception, we need to inside and for me it seems a little bit redundant if we do the dispose inside the “finally” block as we often do for the connection object


Addew,
The using keyword also has a third use … aliasing. You can find more on msdn on this use of the “using” keyword at http://msdn2.microsoft.com/en-us/library/sf0df423.aspx
Thanks Zeberga…
Well, I would still say “using” has two uses , i.e. as “Directive” and as “statement”. For the directive part it has two uses..
*To permit the use of types in a namespace so you do not have to qualify the use of a type in that namespace.
* To create an alias for a namespace.
In this post , I wanted to focus more on the statement part.
Thanks..Bello…