Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have something that works like a fixed size list - it\'s actually called Fixed

ID: 643259 • Letter: I

Question

I have something that works like a fixed size list - it's actually called FixedSizeStack<T> in my program. I will use it to represent the X last occured events. This event list will then be examined by different observers, and if they detect patterns they will trigger some action.

Naturally, I see no reason for them to know of FixedSizeStack<T> - to me it makes sense to present it to the actions as IEnumerable. I am considering giving them this event list in their constructors, then calling something like PreviewEvent(Event e); and EventOccured(); and they will iterate over this IEnumerable.

I feel a little queasy enumerating this IEnumerable multiple times, and making it part of the contract that the enumeration changes - do you think this is a reasonable method?

Explanation / Answer

I don't think it's a code smell at all. The IEnumerable (and IEnumerable<T>) interfaces are simply described as:

Exposes the enumerator, which supports a simple iteration over a collection of a specified type. - MSDN

It's a collection, and it exposes an enumerator. There's nothing in the contract that would imply that that each time you access the enumerator, that it would return the same sequence of elements. Probably a little unconventional, but totally correct.

It is up to the consumer to make assumptions or have requirements about a reference to a collection being passed in. If the consumer really doesn't want the list to change unexpectedly, they should immediately call .ToList() or .ToArray().