Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does foreach use IEnumerator/IEnumerable for built-in types?

Does the foreach loop use interfaces IEnumerator and IEnumerable only for iterating the objects of custom types (classes) or also for iterating the built-in types (behind the scenes)?

like image 310
Prem Avatar asked Dec 29 '25 02:12

Prem


1 Answers

Foreach doesn't depend on IEnumerable as such. However, if a type implements it then a foreach loop will be able to enumerate it (pattern-based matching).

Behind the scenes it only needs a GetEnumerator() method and the enumerator must contain Current and MoveNext().

From MSDN:

  • The collection type:

    • Must be one of the types: interface, class, or struct.
    • Must include an instance method named GetEnumerator that returns a type, for example, Enumerator (explained below).
  • The type Enumerator (a class or struct) must contain:

    • A property named Current that returns ItemType or a type that can be converted to it. The property accessor returns the current element of the collection.
    • A bool method, named MoveNext, that increments the item counter and returns true if there are more items in the collection.

From MSDN - Using foreach with Collections

UPDATED: See updated MSDN page for this - How to: Access a Collection Class with foreach (C# Programming Guide) .

like image 189
David Neale Avatar answered Dec 30 '25 16:12

David Neale



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!