6

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

Code Ratchet
  • 5,758
  • 18
  • 77
  • 141
  • 1
    `using` calls `Dispose` on the object when finished. See: http://msdn.microsoft.com/en-us/library/aa326260(v=vs.71).aspx – Evan Trimboli Nov 03 '14 at 03:46
  • 1
    Can you provide links to those other answers with conflicting opinions? I'd say no close is needed, you can remove that entire `finally` block. – musical_coder Nov 03 '14 at 03:46

3 Answers3

8

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?

Community
  • 1
  • 1
vallabha
  • 385
  • 1
  • 12
1

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

Robert Anderson
  • 1,246
  • 8
  • 11
1

The using will take care of it for you. As additional background, a using statement is syntactic sugar for a try ... finally that disposes the IDisposable object in the finally.

Deepanshu
  • 41
  • 6