Home > Backend Development > C++ > What Types of C# Classes Support Foreach Loops?

What Types of C# Classes Support Foreach Loops?

Patricia Arquette
Release: 2025-01-10 10:18:40
Original
891 people have browsed it

What Types of C# Classes Support Foreach Loops?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template