I know that the following statement is useful for garbage collection. Effectively it must be the same as Try/Catch/finally. If I use it for the sql connection should i also nest a further 'using' statement for a sql adapter? And then a further nested using for the DataSet?
using()
{
}
A further addition to the question is if I want to use the same connection across several methods then is it best practice to have 'Using()' in each of the methods, or can I just create this connection object once?
Something else that is worth pointing out is that you can combine multiple using
statements into one block like this:
using (SqlConnection connection = new SqlConnection("connectionString"))
using (SqlCommand command = new SqlCommand("SELECT * FROM Users", connection))
{
// Do something here...
}
Once you exit this block (either by reaching the end of the block or an exception was thrown), both the SqlConnection
and SqlCommand
object would be disposed automatically.
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