IEnumerable for look up a collection.

  • Thread starter Thread starter Iulian Ionescu
  • Start date Start date
I

Iulian Ionescu

I have seen the following block of code used by many
people to loop through the items in a collection:

IEnumerator e;
IDisposable disposable1;
Object obj1;
e = SomeCollection.GetEnumerator();
try
{
while (e.MoveNext())
{
obj1 = e.Current;
}
}
finally
{
disposable1 = (e as IDisposable);
if (disposable1 != null)
{
disposable1.Dispose();
}
}

However, whenever I use it the disposable1 is always
null, so I do't see the point of the finally block...
Also, as I read the foreach() loop uses the IEnumerator
to loop through the collection. So my question is: is
there any advantage in using the above code over the
foreach loop?

Thank you!!
Iulian
 
Iulian Ionescu said:
I have seen the following block of code used by many
people to loop through the items in a collection: ....
However, whenever I use it the disposable1 is always
null, so I do't see the point of the finally block...
Also, as I read the foreach() loop uses the IEnumerator
to loop through the collection. So my question is: is
there any advantage in using the above code over the
foreach loop?

The IDisposable is always null because you've only run the loop on
enumerators that don't implement that interface. This form ensures that the
enumerator is disposed as quickly as possible, freeing up any resources it
may hold. Being in a finally block ensures that the resources are freed
even if an exception occurs. There is no significant advantage in using
while over foreach, it's just a matter of preferred style.
 
Back
Top