Meeting the needs of your business from a distance

Interesting use of using clause mixed in a generic type

by Mark Shiffer 24. October 2008 22:43

I am currently reading "More Effective C#: 50 Specific Ways to Improve Your C#" by Bill Wagner and came across an interesting piece of syntax that I have not seen before. Below is an excerpt from the book.

Notice how the cast is used in the using statement. The neat thing here is that even if T doesn't support IDisposable, the code will still work, but if it does the object gets properly disposed off. That's nice!

[Begin Excerpt]

public void GetThingsDone()
{
    T driver = new T();
    using (driver as IDisposable)
    {
        driver.DoWork();
    }
}

This may look a bit confusing if you've never seen that sort of cast in a using statement, but it works. The compiler creates a hidden local variable that stores a reference to the driver cast as an IDisposable. If T does not implement IDisposable, then the value of this local variable is null. In those cases, the compiler does not call Dispose(), because it checks against null before doing this extra work. However, in all cases where T implements IDisposable, the compiler generates a call to the Dispose() method upon exiting the using block.

[End Excerpt]

Tags:

Research | Programming

Comments

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Copyright © 2001-2010 MS Consulting, Inc. All Rights Reserved.