Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The usage of the `using` statement in C# when dealing with Database related classes the best practice?

Tags:

c#

database

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...
}
like image 985
Zignd Avatar asked Dec 21 '22 04:12

Zignd


1 Answers

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.

like image 113
Chris Doggett Avatar answered May 19 '23 10:05

Chris Doggett