In .NET world we dont have to worry about the object disposal. However if we are working with unmanaged code than we need to make sure that all objects gets disposed. .NET provides Idisposable interface for this, which we can use to dispose a database connection or flat file connection. Again we can never be sure that dispose method gets called, so best is to wrap the Dispose inside the object destructor or finalizer.
public interface IDisposable
{
void Dispose();
}
Example :
public class ClassDisposable : IDisposable
{
//Flag to check objects are disposed or not
private bool _isDisposed = false;
~ClassDisposable()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(true);
}
//Created virtual method so that child classes
//can call base class dispose method to make sure all resources
//should be properly disposed.
//Avoid calling any other function in Dispose method.
//Just use Dispose it self to destroy all the objects.
//We can never be sure of the order of the objects
//in which they gets disposed.
protected virtual void Dispose(bool isDisposing)
{
if (_isDisposed)
return;
if (isDisposing)
{
// Free managed resources
}
// Free unmanaged resources here
_isDisposed = true;
}
}