What is the requirement for the collection so that we can impose foreach on it?

What is the requirement for a collection so that we can set foreach on it in C #? What are the types by which we can supply for each?

EDIT 1: Can anyone come up with a sample code for a custom collection that runs Foreach.

+4
source share
3 answers

It implements IEnumerable or IEnumerable<T>

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

+5
source

It is generally accepted that you need an implementation of IEnumerable or IEnumerable<T> , but you can read Eric post Following a pattern that is not the case as such

The collection type is required to have a public method called GetEnumerator, and which must return a type that has a public getter property called Current and a public MoveNext method that returns bool.

+3
source

The only formal requirement is that it has a method called GetEnumerator() that returns something that has the SomeType Current {get;} property and the bool MoveNext() method. However, as a rule, this is achieved by implementing the IEnumerable / IEnumerable<T> interface. In fact, it is expected that you will implement this interface (the old method was really intended as pre-generation), and using this interface will allow consumers to use your collection with things like LINQ and collection initializers.

In interesting cases, the easiest way to implement this is to use an โ€œiterator blockโ€. For instance:

 class Foo : IEnumerable<int> { IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerator<int> GetEnumerator() { yield return 16; yield return 12; yield return 31; // ^^ now imagine the above was a loop over some internal structure - // for example an array, list, linked-list, etc, with a "yield return" // per item } } 
+3
source

Source: https://habr.com/ru/post/1398548/


All Articles