Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array of streams in c sharp

Tags:

arrays

c#

stream

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?

like image 834
scott Avatar asked Dec 17 '22 23:12

scott


1 Answers

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.

like image 107
kemiller2002 Avatar answered Dec 24 '22 00:12

kemiller2002