Saturday, January 23, 2010

Implementing Dispose pattern and Destructor in C#

namespace VariousExperiments.disposabl
{
public class GrandParent : System.Object, IDisposable
{
public unsafe IntPtr? pointer;
public unsafe IntPtr? stringPointer;
public List someItems=new List();

// Dispose(bool disposing) executes in two distinct scenarios.
// If disposing equals true, the method has been called directly
// or indirectly by a user's code. Managed and unmanaged resources
// can be disposed.
// If disposing equals false, the method has been called by the
// runtime from inside the finalizer and you should not reference
// other objects. Only unmanaged resources can be disposed.
public virtual void Dispose(bool disposing) {
if (disposing) {
//Dispose the managed resources by calling dispose on them
someItems.GetEnumerator().Dispose();
//Suppress finalize since Dispose is called.
//No need to ask the runtime to call the finalizer over this object
GC.SuppressFinalize(this);
}

//release managed resources
someItems = null;
//Release Unmanaged resources
unsafe
{
pointer = null;
stringPointer = null;
}
}
#region IDisposable Members

public void Dispose()
{
Dispose(true);
}

#endregion

// Use C# destructor syntax for finalization code.
// This destructor will run only if the Dispose method
// does not get called.
// It gives your base class the opportunity to finalize.
// Do not provide destructors in types derived from this class.
~GrandParent() {
Dispose(false);
}

}

public class Parent : GrandParent
{

public override void Dispose(bool disposing)
{
//Release extra resources, if any
base.Dispose(disposing);
}
}

public class Child : Parent {

public override void Dispose(bool disposing)
{
//Release extra resources, if any
base.Dispose(disposing);
}
}
}


--One more time.

We "need" destructor and/or dispose when we have references to unmanaged resources in our object. Since GC knows how to kill (and recollect memory) managed references, it is fine as long as an object doesn't has any unmanaged resource references in it.

No comments:

Post a Comment