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
}
}
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:
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.
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.
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.
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