views:

165

answers:

2

I have an IEnumerable<IDisposable> collection that I need to dispose of at a given point. The issue is that for some cases all the object will be of one type and disposing of the objects needs to be done by collecting some data from them and making a single RPC call. In other cases, the objects will be of another type and I just need to call Dispose on each of them.

I control the code doing this but I'd rather not push implementation details into it.

If I have to I can switch to something like this but it seems inelegant.

with(var rpc = new RPCDisposer())
{
    foreach (var item in Items)
    {
        rpc.Add(item);
        item.Dispose();
    }
}

Edit: the list (for now) will only contain one type or the other, never both. But I'd rather the Dispose code not have to known about the RPC stuff at all, e.i.:

foreach (var item in Items)
    item.Dispose();
+3  A: 

If this depends on the item type then you could do a check on what kind of item you got, adding to RPCDisposer only those of that specific type.

using(var rpc = new RPCDisposer())
{
    foreach (var item in Items)
    {
        if (item is RPCItemType)
            rpc.Add(item);
        item.Dispose();
    }
}

But even better would be if you did not mix those objects in the same list. Could you refactor your code to keep them in two different lists?

Peter Lillevold
see edit.
BCS
OTOH at some point I will be getting a mixed bag (and needing to run several RPCs, one per remote systems) so I might need to just bite the bullet and assume the code needs to sort the items.
BCS
+1  A: 

The OfType method might help you to separate the items into two lists...

var rpcItems = items.OfType<RPCItemType>();    
var normalItems = items.Where(x => !rpcItems.Contains(x));
Joel Mueller
See edit.
BCS