Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to close connection when using a 'using' statement [duplicate]

Currently my code is constructed as follows.

using (var sqlCon = new SqlConnection(Context.ReturnDatabaseConnection()))
        {
            sqlCon.Open();

            try
            {
               //Code here

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                sqlCon.Close();
            }
        }

Ideally from what I understand using the 'using' statement will take care of the connection being closed but I have my doubts due to what other people have said.

Thanks

like image 226
Code Ratchet Avatar asked Mar 19 '23 00:03

Code Ratchet


2 Answers

NO need as object will automatically disposed when we use using blocks. Go through this

http://msdn.microsoft.com/en-us/library/yh598w02.aspx

What is the C# Using block and why should I use it?

like image 157
vallabha Avatar answered Apr 26 '23 12:04

vallabha


Hi just the using statement will be fine. It will dispose the object and generally requires less coding.

like image 21
Robert Anderson Avatar answered Apr 26 '23 14:04

Robert Anderson