Groups | Blog | Home
all groups > dotnet ado.net > july 2007 >

dotnet ado.net : Can you close without Close()?


Gustaf
7/5/2007 12:00:00 AM
Can a database connection be closed without calling the Close() method, like in this example:

using (OleDbConnection c = new OleDbConnection("..."))
{
try
{
// Open connection
c.Open();
}
catch (Exception ex)
{
// Report error
}
}

Or do I need something like:

try
{
// Open connection
OleDbConnection c = new OleDbConnection("...");
c.Open();
}
catch (Exception ex)
{
// Report error
}
finally
{
// Close connection
if (c != null)
c.Close();
}

Are these two equivalent?

Milosz Skalecki [MCAD]
7/5/2007 4:00:01 AM
Howdy Gustaf,

"using" statement in this case is a equivalent to
SqlConnection c = new SqlConnection();
try
{
c.Open();
}
finally
{
if (c != null)
((IDisposable) c).Dispose();
}

so as you can see Dispose() method is being called, which uses Close()
internally. Logically both snippets do exactly the same thing, but if you
plan to handle the exception in the code i would go for the second one.
--
Milosz


[quoted text, click to view]
Milosz Skalecki [MCAD]
7/5/2007 6:04:00 AM
Hi Gustaf,

Sorry i wasn't clear. Dispose is exposed by IDispoable interface (see
there's casting ((IDisposable) c).Dispose(); ) which must be implemented
when using "using" statement. If you have a look at the SqlConnection class
you'll see it implements IDisposable interface. In other words, it's not
possible to apply "using" statement in conjunction with a class that does not
implement this interface, i.e.

using (Random random = new Random())
{
}

would not compile because Random class does not implement IDisposable
interface.

Hope it's clear now.

Regards
--
Milosz


[quoted text, click to view]
Gustaf
7/5/2007 1:25:18 PM
[quoted text, click to view]

Many thanks, Milosz. Somewhat off-topic now, how can Dispose() call Close() internally? Does Dispose() always call a Close() method if there is one?

NadeemIqbal
7/6/2007 3:56:00 AM
Both are bit different.
if u r using using statement it will close as well as dispose the connection
Whereas other will only close the connection

[quoted text, click to view]
Milosz Skalecki [MCAD]
7/6/2007 4:44:03 AM
Hi there,

I checked the code and Dispose for DbConnectionClass just calls Close method
which is responsible for returning the connection to the pool or if pooling
is off releasing all the resources.

Regards
--
Milosz


[quoted text, click to view]
AddThis Social Bookmark Button