0

While studying about IEnumerator and IEnumerator<T>, I came accross the following statement:-

If we call GetEnumerator() on any collection, we mostly get the type-safe version ie "generic" version, notable exception in this case is array which returns the classical(non-generic) version.

My question is that:-
Why do arrays return "classical" Enumerator upon calling the GetEnumerator() function, but other data-structures like List<T> and others return the generic Enumerator?

string[] tempString = "Hello World!" ;
var classicEnumerator = tempString.GetEnumerator() ; // non-generic version of enumerator.
List<string> tempList = new List<string> () ; 
tempList.Add("Hello") ; 
tempList.Add(" World") ; 
var genericEnumerator = tempList.GetEnumerator() ; // generic version of enumerator.
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Pratik Singhal
  • 6,283
  • 10
  • 55
  • 97

1 Answers1

3

This is just because Array predates generics (which were introduced in .NET 2.0).

Actually, arrays also implement the IEnumerable<T> interface, but they do it explicitly. So you can do that:

string[] tempString = new[]{"Hello World!"}; ;
IEnumerable<string> enumerable = tempString;
var genericEnumerator = enumerable.GetEnumerator() ; // generic version of enumerator
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758