-2
private void a()
{

    string query = "";

    using (SqlConnection conn = new SqlConnection("connectionstring here"))
    {
        conn.Open();

        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
            cmd.ExecuteQuery();
        }
        conn.Close();
    }
}

private void B()
{

    string query = "";
    SqlConnection conn = new SqlConnection("connectionstring here");

    conn.Open();

    SqlCommand cmd = new SqlCommand(query, conn);
    cmd.ExecuteQuery();

    conn.Close();
}

Which of the two is better to use? and why?

Tim
  • 28,212
  • 8
  • 63
  • 76
Rey
  • 11
  • 1
  • 3
    Can you please show your code as a plain text instead of image? And "better" is kind of subjective. It would be better to ask if you have a _specific_ problem. – Soner Gönül Feb 02 '16 at 07:16
  • First one since it's using `using`. http://stackoverflow.com/questions/75401/uses-of-using-in-c-sharp – Irshad Feb 02 '16 at 07:17

2 Answers2

2

The first version is better, because you don't have to remember to Close the connection, since SqlConnection is wrapped in a using statement. The conn.Close() call in the first version is not needed. The connection will be closed in the finally block of the using.

Christos
  • 53,228
  • 8
  • 76
  • 108
  • `SqlCommand` *does* implement `IDisposable`, as it derives from `Component`. The code wouldn't even compile otherwise. So yes, I would keep the `using` statement for that. – Jon Skeet Feb 02 '16 at 07:23
  • @JonSkeet I wasn't aware of this :(. I will correct my answer. Thanks – Christos Feb 02 '16 at 07:24
  • I kind of disagree with your _there isn't any need of using a using for the SqlCommand object_ sentence. `SqlCommand` _indirectly_ inherits from `Component` which implements a finalizer. – Soner Gönül Feb 02 '16 at 07:24
  • An additional benefit of the `using` statement is that the object will be disposed of once the `using` block is exited - which means even if an exception is thrown, your connection will still be disposed. That is not the case in your second example. – Tim Feb 02 '16 at 07:24
1

As a rule of thumb:

  • Always dispose IDisposables.
  • It is easiest to do it with using.

So ...

Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193