Typically I declare streams inside of a using statement to ensure that the stream is properly disposed when I am done with it, and so that I don't mistakenly call it when I'm outside the using block.
Some examples here: MSDN using Statement Reference
How does one use a using statement with an array of streams? Would it be equivalent to declare the array outside of a try/catch/finally block and call each stream's dispose method in the finally block?
Lastly, how does one test that the streams have been properly disposed?
I would create a new object that holds the Streams in it. Something like this (not totally fleshed out):
class StreamHolder : IDisposable
{
List<Stream> Streams {get;}
public void Dispose()
{
Streams.ForEach(x=>x.Dispose()):
}
}
This way you can put the container object in the using
statment, it will will handle the stream disposal for you. Your other option is the handle it in the Finally block, but if I were going to do this in more than one place, I would like to encapsulate it, so I don't accidentally forget to dispose of all the streams when I am done.
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