A question that is not clear to me. I see this sample code at
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}
I see that it is not necessary to do command.Dispose()
When you're in such a function, is it good practice to dispose of the elements (for example the Command, DataTable, DataSet, etc.) or just let them "die" at the end of the function?
I always advise that if an object implements
Dispose
, it's good to always use it.Then, as in everything, there are nuances. In the example you give, the
Dispose
delSqlCommand
is not excessively necessary, since an object of this type does not take up many resources and it is not excessively necessary to get rid of it, its management can be left to the GC without major problems.Another thing is the connection
SqlConnection
. In that case, it is important to get rid of the object once used, since it is a direct connection to the database and if we do not manage it well, it can affect its performance. That's why, as you see in the example, a struct is usedusing
.In short, as a general rule, it never hurts to make
Dispose
objects that implement the IDisposable interface , and it's good to get into the habit of doing so.If it is a good practice, since when leaving the keys of the he
using
only manages the execution ofdispose
eg;I can also tell you that I have made a program with
SQLite
(medium large), using a singleusing
as samples in your question, and I did not get any big problems either.In response to your question, the most correct option will be as in the example that I indicated.