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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With