Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the requirement for a collection in order that we can put a foreach on it?

What is the requirement for a collection in order that we can put a foreach on it in c#? What are the types on which we can put for each?

EDIT 1: Can anybody come up with a sample code of a User Defined Collection on which Foreach is Implemented.

like image 998
Rohit Vipin Mathews Avatar asked Dec 22 '22 01:12

Rohit Vipin Mathews


2 Answers

It implements IEnumerable or IEnumerable<T>

Edit: there is the wrinkle that if the type has method called GetEnumerator() that returns an IEnumerator then it is also usable in a foreach. see http://brendan.enrick.com/post/Foreach-IEnumerable-IEnumerator-and-Duck-Typing.aspx

like image 79
Mike Zboray Avatar answered Dec 23 '22 15:12

Mike Zboray


What is generally accepted is that you need implementation of IEnumerable or IEnumerable<T> but you can read from Eric's post Following the pattern that it is not the case as such

What is required is that the type of the collection must have a public method called GetEnumerator, and that must return some type that has a public property getter called Current and a public method MoveNext that returns a bool.

like image 21
V4Vendetta Avatar answered Dec 23 '22 16:12

V4Vendetta