Reputation: 3948
using (FileStream fileStream = new FileStream(path))
{
// do something
}
Now I know the using pattern is an implementation of IDisposable, namely that a Try/Catch/Finally is set up and Dispose is called on the object. My question is how the Close method is handled.
MSDN says that it is not called, but I have read otherwise.
I know that the FileStream inherrits from Stream which is explained here. Now that says not to override Close() because it is called by Dispose().
So do some classes just call Close() in their Dispose() methods or does the using call Close()?
Upvotes: 14
Views: 10564
Reputation: 2044
Close() is not part of the IDisposable interface so using has no way to know whether it should be called or not. using will only call Dispose(), but intelligently designed objects will close themselves in the Dispose() method.
Upvotes: 2
Reputation: 2700
In .Net classes Close() call Dispose(). You should do the same.
Upvotes: 0
Reputation: 97707
I don't think the using calls Close(), it would have no way of knowing that it should call that particular function. So it must be calling dispose, and that in turn is calling close.
Upvotes: 1
Reputation: 1500765
The using
statement only knows about Dispose()
, but Stream.Dispose
calls Close()
, as documented in MSDN:
Note that because of backward compatibility requirements, this method's implementation differs from the recommended guidance for the Dispose pattern. This method calls Close, which then calls Stream.Dispose(Boolean).
Upvotes: 18
Reputation: 122112
using calls Dispose() only. The Dispose() method might call Close() if that is how it is implemented.
Upvotes: 7