views:

70

answers:

4

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 ?

+8  A: 

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.

Darin Dimitrov
+1  A: 

The framework type Array implements IEnumerable...therefore, any array in .NET (of any type) implements IEnumerable.

Justin Niessner
+1  A: 

foreach does not require from type to implement IEnumerable interface, it just needs GetEnumerator() method.

STO
The class needs to implement all the IEnumerable methods, not just GetEnumerator()
Steve Mitcham
@Steve: `IEnumerable` only has a single method, `GetEnumerator`!
LukeH
That's what I get for answering questions first thing in the morning. I was filling in from the MSDN information in my answer on this question, which indicates additional methods are required, which are on the IEnumerator interface.
Steve Mitcham
+2  A: 

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.

Steve Mitcham
For type safety you can (and should) implement IEnumerable<T>
SWeko
I've not found a case where I couldn't just use IEnumerable<T> in my own code, I was just answering the original question of how to get foreach working without using the IEnumerable interface.
Steve Mitcham