Re: Paradigm for multiple IDisposables





"Zach" <divisortheory@xxxxxxxxx> wrote in message news:1158952011.411783.34600@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
I'm sure this comes up often, but I have a situation where I have at
least 4 objects that all implement IDisposable. It gets very tedious
having to write finally blocks that Dispose all of them in a row, but
the using statement is very limited in that it doesn't (seem to) allow
me to have a list of objects specified. Well, I guess that's not
entirely true, if they are all the same type it does, but in my case
they aren't all the same type. I've figured out a couple ways of
handling, but I wonder if there is something more elegant than what I'm
doing. Here's what I've thought of so far:

.. . .

-------------------------------------
Solution 3: Do nothing special, just use tons of nested using
statements. To improve readability, wrap only the innermost using
block with parentheses, and don't indent consecutive using blocks so as
to keep the indentation level small.

Example 3:

using (Disposable1 First = new Disposable1())
using (Disposable2 Second = new Disposable2())
using (Disposable3 Third = new Disposable3())
using (Disposable4 Fourth = new Disposable4())
{
//Code here
}
-------------------------------------


.. . .

Anyone have any thoughts on this problem, or is there a standard
"accepted" way of handling this?

I greatly prefer "Solution 3". It's simple, completely general, readable and works well.

The performance should be fine, especially since use of Disposable objects usually coincides with network access, and so performance considerations on the order of magnitude at which these solutions differ should be irrelevant.

David

.



Relevant Pages

  • Re: Problems with try...catch
    ... I'm not really sure what the using keyword has to do with either error ... handling or Dispose, ... The using directive which makes namespaces ... calls Dispose on implementations of IDisposable automatically. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Why isnt Dispose() implemented in the compiler?
    ... > performance considerations, so I understand the reasoning there, but there's ... the framework could go ahead and call Dispose() right there. ... > When you release the final reference to the object, ...
    (microsoft.public.dotnet.languages.csharp)