Blog

DirectoryEntry Close vs Dispose

February 19, 2008

While I was reading The .NET Developer's Guide to Directory Services Programming yesterday, I came across this passage called Close or Dispose?

There's a class called DirectoryEntry in the System.DirectoryServices namespace which has both a Close and a Dispose method. As it appears,  you get different behavior depending on which of these two methods you call to free up it's memory.

Now, quoting Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries:

CONSIDER proving method Close(), in addition to the Dispose() method, if close is standard terminology in the area. When doing so, it is important that you make the Close implementation identical to Dispose ...

The authors of  The .NET Developer's Guide to Directory Services Programming recommend that one should always use the Dispose method for releasing a DirectoryEntry object, and this for the following reasons:

  • Dispose() suppresses .NET finalization, Close() does not.
  • Calling Close() on a DirectoryEntry object enables rebinding of this object to a different object (NOT recommended).
  • Using .NET 1.x, calling Dispose() is the only way to prevent significant memory leaks due to bugs in the finalization of a DirectoryEntry object. This causes the underlying COM object never to be released. This is fixed with the released of .NET 2.0.

Needless to say that this is not included with the MSDN documentation. Also a violation of their own guidelines. What as shame!

Bottom line, always call Dispose on a DirectoryEntry object. Also make sure that you release DirectoryEntry objects that you get from properties or methods, like the Parent or SchemaEntry property. These properties return a new instance of DirectoryEntry every time you call them (being picky: they should have been methods instead). So make sure you keep a reference so you only have to call them once.

Till next time.

If you and your team want to learn more about how to write maintainable unit tests and get the most out of TDD practices, make sure to have look at our trainings and workshops or check out the books section. Feel free to reach out at infonull@nullprincipal-itnull.be.

Profile picture of Jan Van Ryswyck

Jan Van Ryswyck

Thank you for visiting my blog. I’m a professional software developer since Y2K. A blogger since Y2K+5. Provider of training and coaching in XP practices. Curator of the Awesome Talks list. Past organizer of the European Virtual ALT.NET meetings. Thinking and learning about all kinds of technologies since forever.

Comments

About

Thank you for visiting my website. I’m a professional software developer since Y2K. A blogger since Y2K+5. Author of Writing Maintainable Unit Tests. Provider of training and coaching in XP practices. Curator of the Awesome Talks list. Thinking and learning about all kinds of technologies since forever.

Contact information

(+32) 496 38 00 82

infonull@nullprincipal-itnull.be