July 15, 2005

Generic Dispose

Use this generic class to dispose of any reference object, whether it is IDisposable or not. I havent tried this class yet so I do not know if it will work. It is using c# Generics. I am assuming a C# generic class can have a static method.
public class Disposer<T>
{
  static public void DisposeOf(ref T obj)
  {
    if (!ReferenceEquals(obj, null))
    {
      if (obj is IDisposable)
        ((IDisposable)obj).Dispose();
      obj = null;
    }
  }
}
...
// To use
Disposer<MyClass>.DisposeOf(ref myObject);

No comments: