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]