How to rewrite this snippet if you must implement IDisposable

K

kalamantina

How to rewrite this snippet if you must implement IDisposable


private static void OpenConnection()

{

string connectionString = GetConnectionString();

StringBuilder errorMessages = new StringBuilder();

SqlConnection connection = new
SqlConnection(connectionString);

try

{

connection.Open();

Console.WriteLine("ServerVersion: {0}",
connection.ServerVersion);

Console.WriteLine("State: {0}", connection.State);

}

catch (SqlException ex)

{

for (int i = 0; i < ex.Errors.Count; i++)

{

errorMessages.Append("Index #" + i +
"\n" +

"Message: " + ex.Errors.Message +
"\n" +

"LineNumber: " + ex.Errors.LineNumber +
"\n"
+

"Source: " + ex.Errors.Source +
"\n" +

"Procedure: " + ex.Errors.Procedure +
"\n");

}

Console.WriteLine(errorMessages.ToString());

connection.Close();

}
 
N

Nicholas Paldino [.NET/C# MVP]

Why do you need to implement IDisposable? You are not storing the
connection. Rather, I would move the call to close into a finally clause,
and then check for null before calling close.

Hope this helps.
 
M

Marc Gravell

or - simpler - just be "using" the new SqlConnection (rest of code as-is):

using(SqlConnection connection = new SqlConnection(connectionString)) {
try {
connection.Open();
// blah...
}
// blah...
}

(might also want to be mindful of swallowing too many SqlExceptions and
missing something important...)

Marc
 
K

kalamantina

Hi Nicholas,
I am just asking to see if I can force Dispose on a sql connetion. I
like the finnaly approach cause I already went into a try catch
scenario, but I am stil ltrying to force dispose on it, Any help would
be appreciated.
 

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