In C#, how does one obtain a generic enumerator from a given array?
In the code below, MyArray
is an array of MyType
objects. I'd like to obtain MyIEnumerator
in the fashion shown,
but it seems that I obtain an empty enumerator (although I've confirmed that MyArray.Length > 0
).
MyType [ ] MyArray = ... ;
IEnumerator<MyType> MyIEnumerator
= ( MyArray.GetEnumerator() as IEnumerator<MyType> ) ;
Since I don't like casting, a little update:
To Make it as clean as possible I like to let the compiler do all of the work. There are no casts (so its actually type-safe). No third party Libraries (System.Linq) are used (No runtime overhead).
// And to use the code:
This takes advantage of some compiler magic that keeps everything clean.
The other point to note is that my answer is the only answer that will do compile-time checking.
For any of the other solutions if the type of "arr" changes, then calling code will compile, and fail at runtime, resulting in a runtime bug.
My answer will cause the code to not compile and therefore I have less chance of shipping a bug in my code, as it would signal to me that I am using the wrong type.
You can decide for yourself whether casting is ugly enough to warrant an extraneous library call:
And for completeness, one should also note that the following is not correct--and will crash at runtime--because
T[]
chooses the non-genericIEnumerable
interface for its default (i.e. non-explicit) implementation ofGetEnumerator()
.The mystery is, why doesn't
SZGenericArrayEnumerator<T>
inherit fromSZArrayEnumerator
--an internal class which is currently marked 'sealed'--since this would allow the (covariant) generic enumerator to be returned by default?YourArray.OfType().GetEnumerator();
may perform a little better, since it only has to check the type, and not cast.
What you can do, of course, is just implement your own generic enumerator for arrays.
This is more or less equal to the .NET implemenation of SZGenericArrayEnumerator<T> as mentioned by Glenn Slayden. You should of course only do this, is cases where this is worth the effort. In most cases it is not.