How to rewrite this snippet if you must implement IDisposable

  • Thread starter Thread starter kalamantina
  • Start date Start date
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();

}
 
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.
 
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
 
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.
 
Back
Top