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)?
Does the foreach loop use interfaces IEnumerator and IEnumerable only for iterating the objects
Share
Foreach doesn’t depend on
IEnumerableas 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 containCurrentandMoveNext().From MSDN:
From MSDN – Using foreach with Collections
UPDATED: See updated MSDN page for this – How to: Access a Collection Class with foreach (C# Programming Guide) .