2

I'm currently skimming through some code that reads Active Directory entries and manipulates them. Since I haven't had to do with this kind of stuff, I F12'd the classes (DirectoryEntry, SearchResultCollection, ...), and I found out they all implement the IDisposable interface, but I couldn't see any using blocks in our code.

Are those even necessary in this case (i.e., should I blindly refactor them in)?

Another question of mine regarding this (there are very many instantiated IDisposable objects in the code: Isn't IDisposable making stuff very "ugly" in this case? I mean, I like using statements as they basically free my mind from worrying about things, but in many cases the code has a layout similar to the following:

using (var one = myObject.GetSomeDisposableObject())
using (var two = myObject.GetSomeOtherDisposableObject())
{
  one.DoSomething();
  using (var foo = new DisposableFoo())
  {
    MyMethod(foo);
    using (...)
    using (...)
    {
      ...
    }
  }
}

I feel that this becomes quite unreadable due to high indentation levels (even stacking the using statements). But extracting some of this into new methods can lead to many parameters that need to be passed, since naturally the "inner" code often needs the objects created in the using statements.

What is an elegant way to solve this without losing readability?

InvisiblePanda
  • 1,589
  • 2
  • 16
  • 39
  • For the first part, [this question](http://stackoverflow.com/questions/6362341/dispose-not-working-as-expected-in-directorysearcher) refers to 'memory used by the task increasing constantly' when not disposing of AD references - for the second, a `using` block is syntactic sugar for a `try/finally` with the Dispose call in the `finally` block, which would be an alternative construct allowing you to dispose of everything in one place, reducing indentation. – stuartd Jun 29 '15 at 11:29
  • @stuartd Thanks for the link, that sure looks interesting (I have to read it fully in a minute). As for `try/finally`, ouch! I forgot about that, of course I knew it existed but just didn't think further. Usually, with one or two `using` statements, it's not a preferred way, but with so many I could try using it. Too bad it doesn't automatically keep me from forgetting to `Dispose` of everything I declared above :D Feel free to add this as a short answer! – InvisiblePanda Jun 29 '15 at 11:35
  • Added as answer, cheers. – stuartd Jun 29 '15 at 11:40

1 Answers1

1

For the first part, this question refers to 'memory used by the task increasing constantly' when not disposing of AD references

For the second, a using block is syntactic sugar for a try/finally with the Dispose call in the finally block, which would be an alternative construct allowing you to dispose of everything in one place, reducing indentation

Community
  • 1
  • 1
stuartd
  • 70,509
  • 14
  • 132
  • 163