views:

367

answers:

1

This might seem like a noddy question, but I was looking at this because I heard someone claiming that you must call Close() on a FileStream, even if it is in a using block (and they have code where Close() is being called right at the end of the block).

I know that Close() is meant to call Dispose(), but I thought I'd look deeper since this is .Net 1.1 code, and the bulk of my experience has been with 2.0 on.

One thing that struck me was that the MSDN documentation for FileStream has Dispose() and Dispose(bool) for .Net 2.0 on, but only Dispose(bool) for .Net 1.1.

I thought that might be an oversight, so I used Reflector to look into an assembly - and there too, I see Dispose(bool), but no Dispose().

Is this correct? If so, what's the story here? FileStream works in a using block - which I thought meant it must implement IDisposable which, to my knowledge only declares Dispose().

Is there some compiler magic going on, or am I missing a hidden implementation of Dispose() somewhere (which, presumably, calls Dispose(true) or Dispose(false) ? )

Finally (no pun intended), can you confirm that scoping a FileStream in using block will close stream at scope exit in .Net 1.1?

[edit]

Just to clarify, this is C# code. I understand that VB.Net didn't get the using statement until .Net 2.0, but my understanding is that C# had it in 1.1 (and my 1.1 code here has it in and it compiles)

+6  A: 

It's implemented a little funny, but it's there: The base class for FileStream: System.IO.Stream implements IDisposable (FileStream just inherits it).

The base stream class implements Dispose() explicitly, so you will only see Dispose() if you cast the stream as IDisposeable (which is what using{} does).

Stream.Dispose() calls Stream.Close().

(got all this via Reflector)

JMarsch
Thanks, JMarsch. That all makes sense. Did you have to do anything special to see it in Reflector? I couldn't see it in Stream either (will check again tomorrow)
Phil Nash
I had trouble finding it too -- I was pretty confused at first! The trick is that it's implemented explicitly, and I guess that means that it doesn't sort as you would expect. In Stream, look for "System.IDisposable.Dispose()" It is sorted with the "s"'s, and on top of that, it's greyed out, but it's there. Regards
JMarsch