destructor behaviour

  • Thread starter Thread starter Servé La
  • Start date Start date
S

Servé La

What are the advantages and disadvantages of opening and closing database
connection in a web application in the following examples?

1: using(SqlConnection connection = new SqlConnection()) {}

2:

SqlConnection connection = null;
try
{
connection = new SqlConnection();
}
finally
{
if (connection != null) connection.Close();
}

3. SqlConnection connection = new SqlConnection();
...
connection.Close();

Is there a general preferred way?
 
Not sure what this has to do with destructors but anyway ...

1. Generally the preferred way - you have to write less code and its exception proof - although you cannot reopen the connect after the constryct (which isn't a problem as hte connection variable out of scope

2. More manual, easier to make mistakes but doesa allow you to reopen the connection later in the method

3. A disaster if an exception is thrown between the Open and Close (even though you don't show the Open). Don't do this.

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

What are the advantages and disadvantages of opening and closing database
connection in a web application in the following examples?

1: using(SqlConnection connection = new SqlConnection()) {}

2:

SqlConnection connection = null;
try
{
connection = new SqlConnection();
}
finally
{
if (connection != null) connection.Close();
}

3. SqlConnection connection = new SqlConnection();
...
connection.Close();

Is there a general preferred way?



--
No virus found in this incoming message.
Checked by AVG Anti-Virus.
Version: 7.0.300 / Virus Database: 265.7.1 - Release Date: 19/01/2005



[microsoft.public.dotnet.languages.csharp]
 
Back
Top