Can anyone explain IEnumerable and IEnumerator to me?
For example, when to use it over foreach? what’s the difference between IEnumerable and IEnumerator? Why do we need to use it?
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.
You don’t use
IEnumerable"over"foreach. ImplementingIEnumerablemakes usingforeachpossible.When you write code like:
it’s functionally equivalent to writing:
By "functionally equivalent," I mean that’s actually what the compiler turns the code into. You can’t use
foreachonbazin this example unlessbazimplementsIEnumerable.IEnumerablemeans thatbazimplements the methodThe
IEnumeratorobject that this method returns must implement the methodsand
The first method advances to the next object in the
IEnumerableobject that created the enumerator, returningfalseif it’s done, and the second returns the current object.Anything in .NET that you can iterate over implements
IEnumerable. If you’re building your own class, and it doesn’t already inherit from a class that implementsIEnumerable, you can make your class usable inforeachstatements by implementingIEnumerable(and by creating an enumerator class that its newGetEnumeratormethod will return).