Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is IEnumerable required to use a foreach loop? [duplicate]

I was wondering, when exactly can I use the foreach loop? Do I have to implement IEnumerable?

like image 789
Josh Avatar asked Aug 27 '10 13:08

Josh


1 Answers

There is no need to implement the IEnumerable interface to use the foreach statement. Here is a quote from the MSDN (http://msdn.microsoft.com/en-us/library/9yb8xew9.aspx):

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.

like image 101
DevExpress Team Avatar answered Oct 23 '22 04:10

DevExpress Team