If I have the following situation:
StreamWriter MySW = null; try { Stream MyStream = new FileStream("asdf.txt"); MySW = new StreamWriter(MyStream); MySW.Write("blah"); } finally { if (MySW != null) { MySW.Flush(); MySW.Close(); MySW.Dispose(); } }
Can I just call MySW.Dispose()
and skip the Close even though it is provided? Are there any Stream implimentations that don't work as expected (Like CryptoStream)?
If not, then is the following just bad code:
using (StreamWriter MySW = new StreamWriter(MyStream)) { MySW.Write("Blah"); }
The StreamWriter method is similar. So, reading the code it is clear that that you can call Close() & Dispose() on streams as often as you like and in any order. It won't change the behaviour in any way.
Close() just calls StreamWriter. Dispose() under the bonnet, so they do exactly the same thing. StreamWriter. Dispose() does close the underlying stream.
If your stream is using an operating system handle to communicate with its source, consider using a subclass of SafeHandle for this purpose. This method is called by the public Dispose method and the Finalize method. Dispose invokes the protected Dispose method with the disposing parameter set to true .
The main difference between Close and Dispose in the case of SqlConnectionObject is: An application can call Close more than one time. No exception is generated. If you called Dispose method SqlConnection object state will be reset.
Can I just call MySW.Dispose() and skip the Close even though it is provided?
Yes, that’s what it’s for.
Are there any Stream implementations that don't work as expected (Like CryptoStream)?
It is safe to assume that if an object implements IDisposable
, it will dispose of itself properly.
If it doesn’t, then that would be a bug.
If not, then is the following just bad code:
No, that code is the recommended way of dealing with objects that implement IDisposable
.
More excellent information is in the accepted answer to Close and Dispose - which to call?
I used Reflector and found that System.IO.Stream.Dispose
looks like this:
public void Dispose() { this.Close(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With