Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I have methods which return lists of Disposable instances?

I have a class, instances of which need to be disposed. I also have several classes that produce these instances, either singly or lists of them.

Should I return IList<MyClass> from my methods or should I create a class that is MyClassCollection which is also disposable and return this instead?

EDIT:

My main reason for asking is that I have ended up doing this quite a lot:

IList<MyObject> list = GetList();
foreach(MyObject obj in list)
{
     //do something
     obj.Dispose();
} 

and it seems that I would be better doing:

using (IList<MyObject> list = GetList())
{
     foreach(MyObject obj in list)
     {
     //do something

     } 
}
like image 837
Sam Holder Avatar asked Jan 29 '10 09:01

Sam Holder


3 Answers

It may be easier to generate a sequence of items (IEnumerable<T>) rather than a list - there are ways that you can make the lifetime of each tied into the iterator, so that:

  • you only have one at a time (I assume they are expensive)
  • they get disposed when their time is up
  • they all get disposed, even in error

This is a topic that I explored here using LINQ, but there are other ways too, if your source is (or can be) a sequence.

like image 51
Marc Gravell Avatar answered Oct 04 '22 11:10

Marc Gravell


It depends on how you will use them, both seem reasonable options. If you know that you will need to dispose all the objects at the same time, then perhaps making the list disposable makes sense, but if the objects could have different lifetimes, I would just return an ordinary list.

Perhaps you could make a generic IDisposableList<T> with a constraint on T where T : IDisposable and have your class implement IDisposable by calling Dispose on all its elements? Then you can reuse this class for all your different IDisposable types.

like image 33
Mark Byers Avatar answered Oct 04 '22 11:10

Mark Byers


It is completely up to the client code to call your Dispose() method. Only it knows when it is done using the objects. You cannot help in any way because you don't know what that code will look like. Creating list objects that dispose their elements is not a good idea. The framework contains no collection object that does this. You'll just confuse the client code programmer.

like image 41
Hans Passant Avatar answered Oct 04 '22 12:10

Hans Passant