I have a method that returns a collection of DirectoryEntry objects.
static IEnumerable<DirectoryEntry> Bar(){ ... }
I've been iterating through the collection when I'm finished with it and disposing of each item, but I'm wondering what the best practice is.
Ex.
var foo = Bar();
\\ Do some work
foreach (var f in foo)
{
f.Dispose();
}
CodePudding user response:
Almost. You should take responsibility to Dispose() disposable objects returned from functions, see eg here, probably in a finally
block.
There's no guarantee that you get the same set of DirectoryEntry object every time you enumerate the IEnumerable (ie with foo.GetEnumerator()
or foreach
). You could get new ones every time, and re-enumerating could cause unnecessarary IO. eg this
static int n = 0;
static IEnumerable<int> Bar()
{
for (int i = 0; i < 10; i )
{
yield return n ;
}
}
static void Main(string[] args)
{
var foo = Bar();
var count = foo.Count();
foreach(var i in foo)
{
Console.WriteLine(i);
}
foreach (var i in foo)
{
Console.WriteLine(i);
}
}
will iterate the IEnumrable three times, generating 30 different int
s.
For this reason, you often need to collect an IEnumerable in a List or other ICollection.
var foo = Bar().ToList();
try
{
// Do some work
}
finally
{
foreach (var f in foo)
{
f.Dispose();
}
}
Something like this
foreach (var f in Bar())
{
using (f)
{
//Do some work
}
}
is risky because if Bar()
returns a collection, and you have an exception, the un-enumerated objects won't get disposed.