I have a class that contains methods that calls stored procedures. Some of these stored procedures return data structures others do not. Here is an example of one of the methods.
public DataTable GetProductData(int productID)
{
DataTable dataTable = new DataTable();
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
{
using (SqlConnection sqlConn = new SqlConnection("CONNECTIONSTRING"))
{
using (SqlCommand sqlCmd = new SqlCommand("getProductData", sqlConn))
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("@ID", productID);
sqlConn.Open();
sqlDataAdapter.Fill(dataTable);
}
}
}
return dataTable;
}
This method is used by another program when data access is required. Here is an example of a method that makes use of the above method ...
public DataTable GetProductInfoFromDatabase(int productID)
{
DataLibrary dl = new DataLibrary();
return dl.GetProductData(productID);
}
What I am wondering is how I should dispose of the dl
variable once I have retrieved the data. Will the garbage collection take care of it or should I implement IDisposable in the class where the GetProductData
method is defined? Are the using
statements enough?
Unless your class is holding onto unmanaged resources or otherwise IDisposable
objects; no, you do not need to implement IDisposable
yourself. An empty Dispose
method buys you nothing.
In the code you provided, the using
statements are sufficient. The DataLibrary
object created in GetProductInfoFromDatabase
will be collected by the GC as you expect.