foreach loop in C#
Question:
What types of classes allow the use of foreach loops?
Answer:
Technically, any class that has a public method named GetEnumerator() that returns a type with a bool MoveNext() method and a Current property can be used. However, the most common explanation involves a class that implements IEnumerable or IEnumerable, returning an IEnumerator or IEnumerator.
By extension, any class that implements ICollection or ICollection (e.g., Collection, List, Array (T[])) can support foreach loops.
How it works:
The foreach loop works as follows:
- Initialize a temporary object (tmp) from the GetEnumerator() method of the given object (obj).
- As long as tmp.MoveNext() returns true, the loop body (surrounded by {...}) is executed repeatedly, containing the current value of Current.
Variations:
- If tmp supports IDisposable, use it to dispose of tmp when the loop completes.
- C# 5.0 allows variables like i to be declared inside a loop, whereas in earlier versions they had to be declared outside the loop. This distinction becomes critical when using i in an anonymous method or lambda expression inside a loop.
The above is the detailed content of What Types of C# Classes Support Foreach Loops?. For more information, please follow other related articles on the PHP Chinese website!