50
using (DbConnection conn = new DbConnection())
{
    // do stuff with database
}

Will the using block call conn.Close()?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Craig Johnston
  • 7,467
  • 16
  • 40
  • 47

4 Answers4

67

Yes, it will; the implementation of DbConnection.Dispose() calls Close() (and so do its derived implementations).

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • 1
    Doesn't it depend on whether the derived class has overridden the Dispose(bool) method? If the derived class does not override it and call 'Close()' then the connection will not be closed at the end of the using block (when Dispose is called) – alwayslearning Sep 01 '11 at 13:31
  • 1
    Pretty sure AL's comment is accurate as DBConnection doesn't actually override Dispose provided by System.ComponentModel.Component. In practice though I doubt there are any DBConnection implementations that don't override Dispose and close any connections as a connection class that doesn't clean up after itself would be a pretty poor implementation. – Mr Grok Feb 27 '15 at 11:51
8

Yes - http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.close.aspx

edit: from Microsoft: "The connection is automatically closed at the end of the using block."

vlad259
  • 1,236
  • 10
  • 24
  • 7
    While a link may solve the question it also may contain more information. A small synopsis here is a nice thing to help the reader concentrate on the important points. – NoDataDumpNoContribution Jul 11 '14 at 12:38
8

A using block will ensure the destruction of DbConnection object by calling the Dispose() method. The Dispose() method will in turn call the Close() method and has to wait for it to finish closing the connection to the database.

Yousha Aleayoub
  • 4,532
  • 4
  • 53
  • 64
Roman
  • 10,309
  • 17
  • 66
  • 101
6

surely yes because it will dispose the connection and before disposing the inner logic of the connection calls the close.

Davide Piras
  • 43,984
  • 10
  • 98
  • 147