Can you close without Close()?

G

Gustaf

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?

Gustaf
 
G

Guest

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.
 
G

Gustaf

Milosz said:
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.

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

Gustaf
 
G

Guest

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
 
G

Guest

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
 
G

Guest

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top