Disposing during foreach

1.5k views Asked by At

In this question: Looping through DirectoryEntry or any object hierarchy - C#

The suggested answer for traversing an LDAP tree is to

DirectoryEntry root = new DirectoryEntry(someDN);

DoSomething(root);

function DoSomething(DirectoryEntry de){
    // Do some work here against the directory entry
    if (de.Children != null) {
        foreach (DirectoryEntry child in de.Children) {
            DoSomething(child);
        }
    }
}

My Question is: Do you need to call Dispose() on each child at the end of each iteration? or will the foreach-loop handle the necessary calls to Dispose()? or are they simply not necessary in a foreach-loop (because perhaps the loop re-uses the resources one would otherwise want to Dispose())

1

There are 1 answers

0
Evk On BEST ANSWER

Yes you need to call Dispose on every child. When you call Children property of DirectoryEntry, it actually creates new DirectoryEntries instance. When you enumerate over that instance, it pulls child entries one by one (not all of them at once), and it will not Dispose them (nor anything will reuse them). Since DirectoryEntry is basically COM object - it's quite important to dispose it (it hold unmanaged resources). So correct way is something like this:

function DoSomething(DirectoryEntry de){
    // Do some work here against the directory entry
    if (de.Children != null) {
        foreach (DirectoryEntry child in de.Children) {
            using (child) {
                DoSomething(child);
            }
        }
    }
}