Wednesday, July 26, 2006

New .Net 2.0 Stream.Dispose Methods

The System.IO.Stream abstract class now implements the IDisposable interface fully (explicitly and non-explicitly). What did it do before that?! Stream implemented the interface explicitly, making only interface instances able to call Dispose(). Before .Net 2.0, it was up to you to implement the IDisposable interface and clean up your derived class' resources via an interface object. You can now call Dispose() methods directly from an object that isn't cast to IDisposable.

New method: FileStream fs = new FileStream(@"C:\boot.ini", FileMode.Open, FileAccess.Read) fs.Dispose(); // or simply... - the better practice/pattern using (FileStream fs = new FileStream(@"C:\boot.ini", FileMode.Open, FileAccess.Read)) { // code ... } Old method: FileStream fs = new FileStream(@"C:\boot.ini", FileMode.Open, FileAccess.Read) IDisposable disp = (IDisposable) fs; disp.Dispose();

No comments: