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");
}
Yes, that’s what it’s for.
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.
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?