The using
statement automatically execute the Dispose method contained in IDisposable, database related classes (like SqlConnection, SqlCommand, etc) implement this interface.
So if I going to use this sort of classes should I use a using
statement for the objects creation so the resources will be released at operation end?
For example, I need to use a SqlConnection, SqlCommand, SqlDataAdapter and a DataTable for some reason so I write this code below, is this the best way to do so or should I put the Dispose() at the finally clause of a try... catch... finally?
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString))
using (SqlCommand cmd = new SqlCommand())
using (SqlDataAdapter da = new SqlDataAdapter())
using (DataTable dt = new DataTable())
{
// Do something...
}
The way you have it is correct. The Dispose() methods will automatically call Close(). That's not necessarily true for everything that implements IDisposable, but for the DB-related classes, it is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With