Not logged in - Login

Smart Dispose method using Generics

Sample on how to create a Dispose function that will first check if the object is defined before attempting to dispose it.

Passing the object to a method:

static public void SafeDispose<T>(ref T objCleanUp) where T : IDisposable
{
   // make sure that the object to be disposed actually exists.
   if (objCleanUp != null)
   {
      // dispose of the object.
      objCleanUp.Dispose();

      //objCleanUp = null; // don't do this.
      //objCleanUp = default(T);  // don't do this.
   }
}

Use of an extension method:

static public void SafeDispose<T>(this T objCleanUp) where T : IDisposable
{
   // make sure that the object to be disposed actually exists.
   if (objCleanUp != null)
   {
      // make sure that the object to be disposed actually exists.
      objCleanUp.Dispose();

      //objCleanUp = null; // don't do this.
      //objCleanUp = default(T);  // don't do this.
   }
}

In both of these examples, setting the objCleanUp variable to NULL will not work. You'll get an error. Setting it to 'default(T)' will work, however, it'll also create a new instance of the object. Not exactly what we're looking for here.

So, set the variable to NULL immediately after the call to SafeDispose().