Playing Chicken With Common Sense

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:

   1: class GenericClass<T> where T : new()
   2: {   
   3:    public void SomeMethod()   
   4:    {      
   5:       T obj = new T();
   6:       ...
   7:    }
   8: }

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.

   1: class GenericClass<T> where T : new()
   2: {
   3:    public void SomeMethod()
   4:    {
   5:       T obj = new T();
   6:  
   7:       using (obj as IDisposable)
   8:       {
   9:          ...
  10:       }
  11:    }
  12: }

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().

taken from: http://shrinkify.com/75n

  • 0 Comments
  • E-mail
  • Kick it!
  • Shout it
  • Bookmark and Share

Comments

Control panel

RecentComments

Comment RSS