Lately I experienced a strange error automating Enterprise Architect: iterating through the Element-Collection of Package resultet in an AccessViolationException. It worked fine for the first time, but failed the next time, until I replaced the FOREACH-loop with FOR.
So I did some investigation, and the result was like this: FOREACH creates an instance of an IEnumerator, which keeps state through the course of the FOREACH loop. It runs in an own instance, and repeatedly call’s Current() and Next() operations.
On the other side, “FOR” is some “stupid” thing, running through the object’s list. It’s not running in an own instance, and allocating memory is the user’s responsibility.
The more, iterating through a collection using FOR should include the use of Count() which keeps track of how many elements are currently contained. IEnumerable does not.
Conclusion: when programming COM-Objects (like EA), it might be better, using FOR instead of FOREACH.
Note: rumour has it, that many of the types in System.Collection.Generic will not allocate an enumerator on FOREACH. The following post shows exactly in what circumstances an enumerator is allocated on the heap:
> LINK <
Recent Comments