Is my understanding/implementation of IDisposable correct?
Hi all,
I'm for a C++ background and am moving into C#. I've read a lot of posts and the MSDN entries on the use of "IDisposable" but I want to make sure I've got a right end of the stick before setting up any bad habits.
I've created a Class e.g "Class1" that has among other functions and variables, contains an "SQLConnection" object. Initially I had a method along the lines of Class1.Close to call the SqlConnection.Dispose() when I had finished with the class.
It seems to make more sense to me to implement the Dispose(); method for my Class so I can take advantage of "Using" and be more in line with the language standard.
So far I've followed the MSDN template producing something like this:
public class Class1: IDisposable
{
// Other variables etc
private SqlConnection MISDBConnection = null;
private bool IsDisposed = false;
~Class1()
{
Dispose(false);
}
protected void Dispose(bool disposing)
{
if (!IsDisposed)
{
if (disposing)
{
// Code to dispose of managed resources
}
}
// Code to dispose of unmanaged resources
try
{
this.MISDBConnection.Dispose();
IsDisposed = true;
}
catch (SqlException e) // Temporary
{
string ErrMessage = "";
string ErrCaption = "";
ErrMessage = "Error whilst disposing of Sql Connection:\n\n" + e.Message;
ErrCaption = "Error Number - " + Convert.ToString(e.Number);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
Will that do the job and function correctly? Sometimes I notice people dispose of the managed and unmanaged in the same part of the if statement?
Am I correct in placing a try-catch around the Dispose method of the SQLConnection?
Finally, I'm slightly unclear on the Finalize in this instance, will I have to explicitly specifiy that my ints, strings, other managed objects are deleted by my own fair hand, or will the GC still take care of them?
Thanks for reading all that, and any responses!