Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerator Implementation: Use struct or class?

I noticed that List<T> defines its enumerator as a struct, while ArrayList defines its enumerator as a class. What's the difference? If I am to write an enumerator for my class, which one would be preferable?

EDIT: My requirements cannot be fulfilled using yield, so I'm implementing an enumerator of my own. That said, I wonder whether it would be better to follow the lines of List<T> and implement it as a struct.

like image 653
Hosam Aly Avatar asked Dec 21 '08 14:12

Hosam Aly


2 Answers

Reason List uses a struct enumerator is to prevent garbage generation in foreach statements. This is pretty good reason especially if you are programming for Compact Framework, because CF doesn't have generational GC and CF is usually used on low performance hardware where it can quickly lead to performance issues.

Also, I don't think mutable structs are source of problems in examples some posted, but programmers that don't have good understanding of how value types work.

like image 112
zigzag Avatar answered Sep 21 '22 05:09

zigzag


Any implementation of IEnumerable<T> should return a class. It may be useful for performance reasons to have a GetEnumerator method which returns a struct which provides the methods necessary for enumeration but does not implement IEnumerator<T>; this method should be different from IEnumerable<T>.GetEnumerator, which should then be implemented explicitly.

Using this approach will allow for enhanced performance when the class is enumerated using a foreach or "For Each" loop in C# or vb.net or any context where the code which is doing the enumeration will know that the enumerator is a struct, but avoid the pitfalls that would otherwise occur when the enumerator gets boxed and passed by value.

like image 27
supercat Avatar answered Sep 21 '22 05:09

supercat