Using keyword “using” in code block
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
To enable comments sign up for a Disqus account and enter your Disqus shortname in the Articulate node settings.