Hello everybody
This long title already contain all my question so i just want to give example
MyClass[] array
How this array work with Foreach without implement IEnumerable interface's method ?
Hello everybody
This long title already contain all my question so i just want to give example
MyClass[] array
How this array work with Foreach without implement IEnumerable interface's method ?
Array implements IEnumerable. Quote from the doc:
In the .NET Framework version 2.0, the Array class implements the System.Collections.Generic.IList(T), System.Collections.Generic.ICollection(T), and System.Collections.Generic.IEnumerable(T) generic interfaces. The implementations are provided to arrays at run time, and therefore are not visible to the documentation build tools. As a result, the generic interfaces do not appear in the declaration syntax for the Array class, and there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations). The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throw NotSupportedException.
The framework type Array implements IEnumerable...therefore, any array in .NET (of any type) implements IEnumerable.
foreach does not require from type to implement IEnumerable interface, it just needs GetEnumerator() method.
The following is from MSDN
In C#, it is not absolutely necessary for a collection class to inherit from IEnumerable and IEnumerator in order to be compatible with foreach. As long as the class has the required GetEnumerator, MoveNext, Reset, and Current members, it will work with foreach. Omitting the interfaces has the advantage of enabling you to define the return type of Current to be more specific than Object, which provides type-safety.