views:

438

answers:

1

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> ) ;
+7  A: 

Works on 2.0+:

((IEnumerable<MyType>)myArray).GetEnumerator()

Works on 3.5+ (fancy LINQy, a bit less efficient):

myArray.Cast<MyType>().GetEnumerator()   // returns IEnumerator<MyType>
Mehrdad Afshari
The LINQy code actually returns an enumerator for the result of the Cast method, rather than an enumerator for the array...
Guffa
Guffa: since enumerators provide read-only access only, it's not a big difference in terms of usage.
Mehrdad Afshari
Yours is the first answer I got to work for me ... thank you, Mehrdad.
JaysonFix