Home > Backend Development > C++ > Which C# Object Types Support foreach Loops and How Do They Work?

Which C# Object Types Support foreach Loops and How Do They Work?

Susan Sarandon
Release: 2025-01-10 10:48:40
Original
598 people have browsed it

Which C# Object Types Support foreach Loops and How Do They Work?

foreach loop in C#

Q: Which object types support foreach loop?

Answer: The core use of the foreach loop requires a MoveNext() method that returns an object with a Current method and a GetEnumerator() property. Simply put, the most common types are those that implement IEnumerable/IEnumerable<T>. This includes implementations of ICollection/ICollection<T>, such as Collection<T>, List<T>, arrays, etc.

How does it work?

A foreach(int i in obj) {...} loop of the form foreach is essentially equivalent to:

<code class="language-csharp">var tmp = obj.GetEnumerator();
int i; // C# 4.0及之前版本
while(tmp.MoveNext()) {
    int i; // C# 5.0及之后版本
    i = tmp.Current;
    {...} // 你的代码
}</code>
Copy after login
The

IEnumerator object (tmp) is used to iterate over the elements of the collection and assign them to the loop variable on each iteration. If the enumerator supports the Dispose() method, it is called just like using the using statement.

Note: The location of the loop variable declaration "int i" differs between C# 4.0 and C# 5.0. C# 5.0 declares it inside the loop, while C# 4.0 declares it outside the loop. This distinction is important when using loop variables in closures or lambda expressions within loops.

The above is the detailed content of Which C# Object Types Support foreach Loops and How Do They Work?. 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