Class Finalizer
A class finalizer helps the .net garbage collector to clean up resources no linger needed by your classes. Personally I use these mostly in base classes, so any derived classes are correctly disposed. Of course this also means correctly implementing IDisposable too.
The syntax of a class finalizer is
public class Base : IDisposable
{
//SQL query object used in derrived classes
internal SqlCommand query = null;
//Constructor
public BaseClass()
{
}
//Finalizer
~Base
{
Dispose(false);
}
//Implemtation of IDisposable
public void Dispose()
{
Dispose(true);
}
//Implemtation of IDisposable
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (query != null)
{
if (query.Connection.State != ConnectionState.Closed)
{
query.Connection.Close();
}
query.Dispose();
}
}
}
}
The base class can then be inherited from as follows:
public InheritingClass : Base
{
public InheritingClass()
{
}
}
InheritingClass inheritingClass = new InheritingClass();
inheritingClass.Dispose()
However the .net garbage collector will also execute the finalizer code whenever it performs its cleanup operations.