Freshblood
Freshblood

Reputation: 6431

How Array of our custom classes work with foreach without implemented IEnumerable?

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 ?

Upvotes: 2

Views: 428

Answers (4)

Steve Mitcham
Steve Mitcham

Reputation: 5313

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.

Upvotes: 3

STO
STO

Reputation: 10638

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

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245419

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

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

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.

Upvotes: 11

Related Questions