1

When I am querying the database from my c# code I usually use something like this construction:

using (var connection = new OleDbConnection(connStr))
using (var command = new OleDbCommand(query, connection))
using (var adapter = new OleDbDataAdapter(command))
{///}

Should I actually use all this 'using' or it will be enough to dispose only connection and all related objects will be disposed too?

Arsen
  • 23
  • 3

3 Answers3

3

it will be enough to dispose only connection and all related objects will be disposed too?

No. Disposing connection will only dispose the connection object.

Generally it is a safe practice to dispose every object that implements IDisposable. (One more thing, disposing Command object will not dispose the related connection object)

Habib
  • 205,061
  • 27
  • 376
  • 407
3

Using statement only dispose the instance that includes. It doesn't effect the other objects that related on that.

You use the right way in your case.

using (var connection = new OleDbConnection(connStr))
using (var command = new OleDbCommand(query, connection))
using (var adapter = new OleDbDataAdapter(command))
{

} // <-- Both connection, command and adapter disposed here
Soner Gönül
  • 91,172
  • 101
  • 184
  • 324
0

Short answer: no, this would only dispose your connection object. You therefore need all these using.

Long(er) answer: behind the using syntax, the compiler creates a scope in which the variable is created (the variable doesn't exist outside of the using scope) and the Dispose method will be called when exiting the using scope.

Therefore, if you don't create your command variable in a using block, the Dispose method will not be called and therefore the object won't be disposed. (unless you decide to call command.Dispose() yourself)

Alex Sanséau
  • 6,440
  • 3
  • 17
  • 24