-1

I'm running the following code and I'm unsure whether the adapter (and the instance of SqlCommand, which I suspect resides in it) gets properly GCed. Also, I'm a bit unsure how to check it, other than asking on SO.

using (SqlConnection connection = new SqlConnection(...))
{
  String command = ...
  DataTable output = new DataTable();
  SqlDataAdapter adapter = new SqlDataAdapter(command, connection);
  adapter.Fill(parameters);
}

I'm assuming that closing the connection isn't necessary as it gets killed and destroyed when the scope of its declaration ends. Is that correct or am I missing something sneaky?

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
  • 3
    Didnt you ask this question? http://stackoverflow.com/questions/18205560/do-i-need-to-explicitly-dispose-sqldataadapter – jamesSampica Aug 08 '14 at 15:12
  • _"closing the connection isn't necessary as it gets killed and destroyed when the scope of its declaration ends."_ No. Nothing is ever automatically disposed, **except via using**. Objects are not collected when they go out of scope - gargage collection happens later, intermittently, and is non-deterministic. If you for example call this method(without the using) in a loop it's possible that the connection doesn't get closed which could cause exceptions(f.e. "too many open connection") or performance issue. – Tim Schmelter Aug 08 '14 at 15:20
  • 2
    No! **NEVER**! This is an entirely different user bearing the same name. He seems to use a similar image as an avatar. The linkage to **my** profile is a bug in SO. Any other issue pointed out is a subject to an excuse and more BS, hahaha. Seriously though, I'm very embarr **assed**. It was almost precisely one year ago so I guess I'm unable to learn... :) – Konrad Viltersten Aug 08 '14 at 15:32
  • @TimSchmelter But I **do** have a *using*. It's its scope I was referring to. So I guess I'm safe. :) – Konrad Viltersten Aug 08 '14 at 15:33

1 Answers1

1

Yes. When your code reaches the end of the using statement, your connection and everything in it is marked for the garbage collector to come by and clean it up when it's cycle comes around.

MikeV
  • 585
  • 3
  • 11