Can someone share a simple example of using the foreach keyword with custom objects?
Can someone share a simple example of using the foreach keyword with custom objects?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Given the tags, I assume you mean in .NET – and I’ll choose to talk about C#, as that’s what I know about.
The
foreachstatement (usually) usesIEnumerableandIEnumeratoror their generic cousins. A statement of the form:where
sourceimplementsIEnumerable<Foo>is roughly equivalent to:Note that the
IEnumerator<Foo>is disposed at the end, however the statement exits. This is important for iterator blocks.To implement
IEnumerable<T>orIEnumerator<T>yourself, the easiest way is to use an iterator block. Rather than write all the details here, it’s probably best to just refer you to chapter 6 of C# in Depth, which is a free download. The whole of chapter 6 is on iterators. I have another couple of articles on my C# in Depth site, too:As a quick example though:
To implement
IEnumerable<T>for a type, you can do something like: