This is another one in the series “heck, I never thought of that”… Like most of these articles, if you already knew this trick, ignore me…

Let’s say you have a generic class with a new() constraint on the type parameter. This means that you are allowed to create new objects of the generic type, like this:

class GenericClass<T> where T:new()
{
   public void SomeMethod()
   {
      T obj = new T();
      ...
   }
}

Pretty straightforward stuff, BUT there is a possibility that type T implements IDisposable, meaning that you should clean up after using any object of type T (using the Dispose method or a “using” block.

The trivial way of solving this problem is:

class GenericClass<T> where T:new()
{
   public void SomeMethod()
   {
      T obj = new T();

      ...

      if (obj is IDisposable)
         ((IDisposable) obj).Dispose();
   }
}

Not too bad, but we can do better:

class GenericClass<T> where T:new()
{
   public void SomeMethod()
   {
      T obj = new T();

      using (obj as IDisposable)
      {
         ...
      }
   }
}

Pretty neat, don’t you think? What actually happens is that the using block creates a “hidden” variable of type “IDisposable” and will call Dispose() on it when exiting the scope of the using block. If T does not implement IDisposable, the hidden variable will be null, and the compiler will not try to call Dispose().

Share this article:
  • Digg
  • StumbleUpon
  • del.icio.us
  • Twitter
  • DotNetKicks
  • DZone
  • LinkedIn
  • Reddit
  • Tumblr